在kotlinx.coroutines库中,您可以使用launch(with join)或async(with await)启动新的协同程序.他们之间有什么区别?
Kotlin协程可以用于生产,它们的实验状态意味着什么?
使用channel.close()关闭kotlinx.coroutines通道的原因是什么以及不手动关闭通道的负面影响是什么?如果我不手动关闭频道会有一些不必要的处理?是否会在某个地方引用阻止其成为GCd的频道?或者,关闭功能是否仅作为向渠道的潜在用户通知其不再可以使用的方式存在.
(转自Kotlin论坛的问题https://discuss.kotlinlang.org/t/closing-coroutine-channels/2549)
我正在生产项目,从多个协同例程中消耗并推回到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() …Run Code Online (Sandbox Code Playgroud) 在kotlinx.coroutines库中,所有协同构建器(如launch,async等)都接受CoroutineContext参数,但也有parent一个类型为的附加参数Job.CoroutineContext和之间有什么区别Job?