【问题标题】:Kotlin: receiving elements in different coroutine is not working properlyKotlin:在不同的协程中接收元素无法正常工作
【发布时间】:2019-02-07 22:30:39
【问题描述】:

我下面有 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")

【问题讨论】:

  • 如果“另一个协程”是指带有 launch 的注释行,我可以分享它在我的机器上正常工作。 Kotlin 1.3.21,协程核心 1.1.1。
  • @MarkoTopolnik - 我已经更新了这个问题。如果它没有意义,请阅读并告诉我。
  • 好的,所以你确认你的意思是我的理解。它在这里工作。

标签: kotlin kotlinx.coroutines


【解决方案1】:

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

导入 kotlinx.coroutines.* 导入 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") }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 2021-04-12
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多