8

我正在生产项目,从多个协同程序中消费并推回 resultChannel。Producer 在最后一项之后关闭其频道。

代码永远不会完成,因为 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}")
4

1 回答 1

7

您可以运行一个协程等待消费者完成,然后关闭resultChannel.

首先,重写启动消费者保存Jobs 的代码:

val jobs = (1..threads).map {
    launch(CommonPool) {
        bundleProducer.consumeEach {
            println("CONSUMING $it")
            resultChannel.send("Result ($it)")
        }
    }
}

然后运行另一个协程,在所有Jobs 完成后关闭通道:

launch(CommonPool) {
    jobs.forEach { it.join() }
    resultChannel.close()
}
于 2017-07-31T12:26:39.813 回答