Kotlin:接收不同协程中的元素不能正常工作

问题描述 投票:0回答:1

我在kotlin coroutine代码下面。

    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")

kotlin kotlinx.coroutines
1个回答
0
投票

原因是您的频道未关闭,因此您的for-each循环可能永远不会结束。如果你在repeat块后关闭你的频道,你的代码将优雅地完成:

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)
        }
        channel.close()
    }

    delay(1000)

    launch {  for (y in channel) println("receiving $y") }

}
© www.soinside.com 2019 - 2024. All rights reserved.