Ниже приведен код сопрограммы 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()
}
Вывод вышеуказанной программы (в котором отсутствует несколько элементов в конце приема) -
sending 1
sending 2
received 2 isClosedForSend false isClosedForReceive false
sending 3
sending 4
received 4 isClosedForSend false isClosedForReceive false
sending 5
Если я раскомментируюстрока if (!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)
Как я могу получить правильный вывод без каких-либо исключений?