trySend
Attempts to add the specified element to this channel without waiting.
trySend never suspends and never throws exceptions. Instead, it returns a ChannelResult that encapsulates the result of the operation. This makes it different from send, which can suspend and throw exceptions.
If this channel is currently full and cannot receive new elements at the time or is closed, this function returns a result that indicates a failure. In this case, it is guaranteed that the element was not delivered to the consumer and the onUndeliveredElement
callback, if one is provided during the Channel's construction, does not get called.
trySend can be used as a non-suspend
alternative to send in cases where it's known beforehand that the channel's buffer can not overflow.
class Coordinates(val x: Int, val y: Int)
// A channel for a single subscriber that stores the latest mouse position update.
// If more than one subscriber is expected, consider using a `StateFlow` instead.
val mousePositionUpdates = Channel<Coordinates>(Channel.CONFLATED)
// Notifies the subscriber about the new mouse position.
// If the subscriber is slow, the intermediate updates are dropped.
fun moveMouse(coordinates: Coordinates) {
val result = mousePositionUpdates.trySend(coordinates)
if (result.isClosed) {
error("Mouse position is no longer being processed")
}
}