Search code examples
kotlin-coroutineskotlin-coroutine-channel

Call conditions for the three on functions of kotlinx.coroutines.channels.ChannelResult


onSuccess is very clear, it will be called when the element is received, onFailure and onClosed will not be called at this time.

But in practice, onFailure and onClosed are a little unclear, most of the time onFailure and onClosed call together. But what are the scenarios where onFailure or onClosed is called alone?


Solution

  • Documentation is pretty clear about the difference:

    It encapsulates the knowledge of whether the operation succeeded, failed with an option to retry, or failed because the channel was closed. (...) If the operation failed, it does not necessarily mean that the channel itself is closed. For example, ReceiveChannel.receiveCatching and ReceiveChannel.tryReceive can fail because the channel is empty, and Channel.trySend can fail because the channel is full.

    We can easily see this in action:

    val ch = Channel<Int>()
    val result = ch.trySend(1)
    println(result.isFailure) // true
    println(result.isClosed) // false
    

    Because isClosed is false, we know we could try resending the same item at a later time.

    I assume the opposite scenario can't take place. true for isClosed implies isFailure is also true.