Die*_*rin 3 kotlin kotlin-coroutines kotlinx.coroutines.channels
考虑以下代码:
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
val channel = Channel<String>()
launch {
channel.send("A1")
channel.send("A2")
log("A done")
}
launch {
channel.send("B1")
log("B done")
}
launch {
for (x in channel) {
log(x)
}
}
}
fun log(message: Any?) {
println("[${Thread.currentThread().name}] $message")
}
Run Code Online (Sandbox Code Playgroud)
原始版本的接收器协程如下:
launch {
repeat(3) {
val x = channel.receive()
log(x)
}
}
Run Code Online (Sandbox Code Playgroud)
它预计通道中只有 3 条消息。如果我将其更改为第一个版本,那么我需要在所有生产者协程完成后关闭通道。我怎样才能做到这一点?
一个可能的解决方案是创建一个等待所有任务channel.send()完成的作业,并调用channel.close()该invokeOnCompletion作业的:
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
val channel = Channel<String>()
launch {
launch {
channel.send("A1")
channel.send("A2")
log("A done")
}
launch {
channel.send("B1")
log("B done")
}
}.invokeOnCompletion {
channel.close()
}
launch {
for (x in channel) {
log(x)
}
}
}
fun log(message: Any?) {
println("[${Thread.currentThread().name}] $message")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1061 次 |
| 最近记录: |