close

abstract fun close(cause: Throwable? = null): Boolean(source)

Closes this channel so that subsequent attempts to send to it fail.

Returns true if the channel was not closed previously and the call to this function closed it. If the channel was already closed, this function does nothing and returns false.

The existing elements in the channel remain there, and likewise, the calls to send an onSend that have suspended before close was called will not be affected. Only the subsequent calls to send, trySend, or onSend will fail. isClosedForSend will start returning true immediately after this function is called.

Once all the existing elements are received, the channel will be considered closed for receive as well. This means that receive will also start throwing exceptions. At that point, isClosedForReceive will start returning true.

If the cause is non-null, it will be thrown from all the subsequent attempts to send to this channel, as well as from all the attempts to receive from the channel after no elements remain.

If the cause is null, the channel is considered to have completed normally. All subsequent calls to send will throw a ClosedSendChannelException, whereas calling receive will throw a ClosedReceiveChannelException after there are no more elements.

val channel = Channel<Int>()
channel.send(1)
channel.close()
try {
channel.send(2)
error("The channel is closed, so this line is never reached")
} catch (e: ClosedSendChannelException) {
// expected
}