Coroutines - detecting when channel is closed with openSubscription()


#1

How would I check if the channel I’m listening with has been closed with this existing code?

val subscription = channel.openSubscription()

for (msg in subscription) {
    // check if msg is close token?
}

Reading the guide it looks like you check if the received value is null, but it looks like this isn’t possible when iterating through the subscription. What’s the correct way?


#2

AFAIK the iterator will just end when the channel is closed, so it should be closed after the for loop ends. If the channel is just empty the iterator will suspend until another element is received by the channel (link to the documentation).

If you don’t want to iterate the channel you can use isClosedForReceive or isClosedForSend depending on what you need.
The guide you mentioned just states that there are 2 options of getting a value from a channel: receive and receiveOrNull, the first suspending if the channel is closed and the other just returning null.
If you are inside of a Select Expression you would use either onReceive or onReceiveOrNull. onReceive will throw an exception if the channel is closed.

Also if you just want to iterate received elements from a Publisher you might want to take a look at consumeEach. That way you don’t have to manually unsubscribe from it.


#3

Thanks so much!