cancel
Closes the channel for new elements and removes all existing ones.
A cause can be used to specify an error message or to provide other details on the cancellation reason for debugging purposes. If the cause is not specified, then an instance of CancellationException with a default message is created to close the channel.
If the channel was already closed, cancel only has the effect of removing all elements from the channel.
Immediately after the invocation of this function, isClosedForReceive and, on the SendChannel side, isClosedForSend start returning true
. Any attempt to send to or receive from this channel will lead to a CancellationException. This also applies to the existing senders and receivers that are suspended at the time of the call: they will be resumed with a CancellationException immediately after cancel is called.
If the channel has an onUndeliveredElement
callback installed, this function will invoke it for each of the elements still in the channel, since these elements will be inaccessible otherwise. If the callback is not installed, these elements will simply be removed from the channel for garbage collection.
val channel = Channel<Int>()
channel.send(1)
channel.send(2)
channel.cancel()
channel.trySend(3) // returns ChannelResult.isClosed
for (element in channel) { println(element) } // prints nothing
consume and consumeEach are convenient shorthands for cancelling the channel after the single consumer has finished processing.