onReceive
Clause for the select expression of the receive suspending function that selects with the element received from the channel.
The select invocation fails with an exception if the channel is closed for receive
at any point, even if other select clauses could still work.
Example:
class ScreenSize(val width: Int, val height: Int)
class MouseClick(val x: Int, val y: Int)
val screenResizes = Channel<ScreenSize>(Channel.CONFLATED)
val mouseClicks = Channel<MouseClick>(Channel.CONFLATED)
launch(Dispatchers.Main) {
while (true) {
select {
screenResizes.onReceive { newSize ->
// update the UI to the new screen size
}
mouseClicks.onReceive { click ->
// react to a mouse click
}
}
}
}
Content copied to clipboard
Like receive, onReceive obeys the rules of prompt cancellation: select may finish with a CancellationException even if an element was successfully retrieved, in which case the onUndeliveredElement
callback will be called.