onSend

Clause for the select expression of the send suspending function that selects when the element that is specified as the parameter is sent to the channel. When the clause is selected, the reference to this channel is passed into the corresponding block.

The select invocation fails with an exception if the channel is closed for send before the select suspends (see the "Sending to a closed channel" section of send).

Example:

val sendChannels = List(4) { index ->
Channel<Int>(onUndeliveredElement = {
println("Undelivered element $it for $index")
}).also { channel ->
// launch a consumer for this channel
launch {
withTimeout(1.seconds) {
println("Consumer $index receives: ${channel.receive()}")
}
}
}
}
val element = 42
select {
for (channel in sendChannels) {
channel.onSend(element) {
println("Sent to channel $it")
}
}
}

Here, we start a select expression that waits for exactly one of the four onSend invocations to successfully send the element to the receiver, and the other three will instead invoke the onUndeliveredElement callback. See the "Undelivered elements" section in the Channel documentation for details on handling undelivered elements.

Like send, onSend obeys the rules of prompt cancellation: select may finish with a CancellationException even if the element was successfully sent.