不能';使用kotlin通道无法接收少量消息

不能';使用kotlin通道无法接收少量消息,kotlin,kotlinx.coroutines,Kotlin,Kotlinx.coroutines,我有下面的kotlin合作程序代码 import kotlinx.coroutines.* import kotlinx.coroutines.channels.* fun main() = runBlocking { val channel = Channel<Int>() val job = launch { for(x in 1..5) { println("s

我有下面的kotlin合作程序代码

    import kotlinx.coroutines.*
    import kotlinx.coroutines.channels.*

    fun main() = runBlocking {

        val channel =  Channel<Int>()
        val job = launch {
            for(x in 1..5) {
                println("sending $x")
                channel.send(x)
            }

            channel.close()
        }

        for (y in channel) {
            // if (!channel.isClosedForReceive && !channel.isClosedForSend)
            println( "received ${channel.receive()} isClosedForSend ${channel.isClosedForSend} isClosedForReceive ${channel.isClosedForReceive}  " )
        }
        job.join()
    }
如果(!channel.isClosedForReceive&&!channel.isClosedForSend)不注释行
,则会得到相同的输出,但有例外

    sending 1
    sending 2
    received 2 isClosedForSend false isClosedForReceive false  
    sending 3
    sending 4
    received 4 isClosedForSend false isClosedForReceive false  
    sending 5
    Exception in thread "main" kotlinx.coroutines.channels.ClosedReceiveChannelException: Channel was closed
        at kotlinx.coroutines.channels.Closed.getReceiveException(AbstractChannel.kt:1081)
        at kotlinx.coroutines.channels.AbstractChannel.receiveResult(AbstractChannel.kt:577)
        at kotlinx.coroutines.channels.AbstractChannel.receive(AbstractChannel.kt:570)
如何才能毫无例外地获得正确的输出?

您只需编写

for (y in channel) {
    println(y)
}
你可以直接写

for (y in channel) {
    println(y)
}