I have below kotlin coroutine code.
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()
}
The output of the above program is (which is missing few elements at receive end) -
sending 1
sending 2
received 2 isClosedForSend false isClosedForReceive false
sending 3
sending 4
received 4 isClosedForSend false isClosedForReceive false
sending 5
If I unncomment the line if (!channel.isClosedForReceive && !channel.isClosedForSend)
, I get same output with exception.
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)
How can I get the correct output without any exception?
You can just write
for (y in channel) {
println(y)
}