ato*_*tok 7 channel coroutine kotlin kotlinx.coroutines
我正在生产项目,从多个协同例程中消耗并推回到resultChannel.制作人在最后一个项目后关闭其频道.
代码永远不会完成,因为resultChannel永远不会被关闭.如何检测并正确完成迭代以便hasNext()返回false?
val inputData = (0..99).map { "Input$it" }
val threads = 10
val bundleProducer = produce<String>(CommonPool, threads) {
inputData.forEach { item ->
send(item)
println("Producing: $item")
}
println("Producing finished")
close()
}
val resultChannel = Channel<String>(threads)
repeat(threads) {
launch(CommonPool) {
bundleProducer.consumeEach {
println("CONSUMING $it")
resultChannel.send("Result ($it)")
}
}
}
val iterator = object : Iterator<String> {
val iterator = resultChannel.iterator()
override fun hasNext() = runBlocking { iterator.hasNext() }
override fun next() = runBlocking { iterator.next() }
}.asSequence()
println("Starting interation...")
val result = iterator.toList()
println("finish: ${result.size}")
Run Code Online (Sandbox Code Playgroud)
您可以运行一个协程,等待消费者完成操作然后关闭resultChannel。
首先,重写启动使用者以保存Jobs 的代码:
val jobs = (1..threads).map {
launch(CommonPool) {
bundleProducer.consumeEach {
println("CONSUMING $it")
resultChannel.send("Result ($it)")
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在所有Jobs完成后,运行另一个协程关闭该通道:
launch(CommonPool) {
jobs.forEach { it.join() }
resultChannel.close()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
338 次 |
| 最近记录: |