我有下面的kotlin协程代码。
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking <Unit> {
val channel = Channel<Int>(4)
val sender = launch (coroutineContext) {
repeat(10) {
println("sending $it")
channel.send(it)
delay(100)
}
}
delay(1000)
//launch { for (y in channel) println("receiving $y") }
for (y in channel) println("receiving $y")
}它工作得很好。如果我将从通道接收元素的逻辑放到另一个协程中(例如,像注释代码中那样将for放在launch中),那么它会在下面的输出中受到攻击(即,我希望发送和接收到10,但它在receiving 3中被卡住了)。
sending 0
sending 1
sending 2
sending 3
sending 4
receiving 0
receiving 1
receiving 2
receiving 3如何在另一个协程中无故障地接收元素?
我使用的是compile("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1")版本
发布于 2019-03-01 14:13:36
原因是您的通道未关闭,因此您的for-each循环可能永远不会结束。如果在repeat块之后关闭通道,则代码将优雅地完成:
导入kotlinx.coroutines。*导入kotlinx.coroutines.channel。*
fun main() = runBlocking <Unit> {
val channel = Channel<Int>(4)
val sender = launch (coroutineContext) {
repeat(10) {
println("sending $it")
channel.send(it)
delay(100)
}
channel.close()
}
delay(1000)
launch { for (y in channel) println("receiving $y") }
}https://stackoverflow.com/questions/54583304
复制相似问题