kotlinchannelkotlin-coroutineskotlin-coroutine-channel

Kotlin Channels usage difference between Send and Offer


Channels have two functions that allow us to send events into it. Send and offer.

I would like to understand better the difference between both.

I have some statements I wanna check are true.

If you know any other main difference I would be glad to know.

Thanks in advance


Solution

  • send suspends the coroutine it is invoked from while the channel being sent to is full.

    send does not send from one channel to another one. When you invoke send you are sending an element to the channel. The channel then expects another block of code to invoke receive from a different coroutine.

    In a RendezvousChannel the capacity is 0. This means that send always suspends waiting for a receive invocation from another coroutine. If you have invoked send on a RendezvousChannel and then use offer, offer will not throw an exception (it only does if the channel is closed), but rather it will return false if no balancing receive has been invoked on the RendezvousChannel after your initial send. This is because offer tries to immediately add the element to the channel if it doesn't violate its capacity restrictions.