isEmpty
Returns true
if the channel contains no elements and isn't closed for receive
.
If isEmpty returns true
, it means that calling receive at exactly the same moment would suspend. However, calling receive immediately after checking isEmpty may or may not suspend, as new elements could have been added or removed or the channel could have been closed for receive
between the two invocations. Consider using tryReceive in cases when suspensions are undesirable:
// DANGER! THIS CHECK IS NOT RELIABLE!
while (!channel.isEmpty) {
// can still suspend if other `receive` happens in parallel!
val element = channel.receive()
println(element)
}
// DO THIS INSTEAD:
while (true) {
val element = channel.tryReceive().getOrNull() ?: break
println(element)
}
Content copied to clipboard