isClosedForSend
Returns true
if this channel was closed by an invocation of close or its receiving side was cancelled. This means that calling send will result in an exception.
Note that if this property returns false
, it does not guarantee that a subsequent call to send will succeed, as the channel can be concurrently closed right after the check. For such scenarios, trySend is the more robust solution: it attempts to send the element and returns a result that says whether the channel was closed, and if not, whether sending a value was successful.
// DANGER! THIS CHECK IS NOT RELIABLE!
if (!channel.isClosedForSend) {
channel.send(element) // can still fail!
} else {
println("Can not send: the channel is closed")
}
// DO THIS INSTEAD:
channel.trySend(element).onClosed {
println("Can not send: the channel is closed")
}
The primary intended usage of this property is skipping some portions of code that should not be executed if the channel is already known to be closed. For example:
if (channel.isClosedForSend) {
// fast path
return
} else {
// slow path: actually computing the value
val nextElement = run {
// some heavy computation
}
channel.send(nextElement) // can fail anyway,
// but at least we tried to avoid the computation
}
However, in many cases, even that can be achieved more idiomatically by cancelling the coroutine producing the elements to send. See produce for a way to launch a coroutine that produces elements and cancels itself when the channel is closed.
isClosedForSend can also be used for assertions and diagnostics to verify the expected state of the channel.