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.
Send
is a suspend function. What will make my code(not the thread) wait for it to finish. So it keep running after the event insidesend
was complete/cancelled. OR it will be suspend only until I can queue the event/receive it?- This means that, if I use
send
from one channel to another, the first channel will be block until the second can receive/queue? - If I have a Rendezvous Channel and it is already running something (on suspend for example, waiting API) and I
offer
a new even. This will makeoffer
throws exception? Cause the channel is not receiving?
If you know any other main difference I would be glad to know.
Thanks in advance
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 invokesend
you are sending an element to the channel. The channel then expects another block of code to invokereceive
from a different coroutine.In a
RendezvousChannel
the capacity is0
. This means thatsend
always suspends waiting for areceive
invocation from another coroutine. If you have invokedsend
on aRendezvousChannel
and then useoffer
,offer
will not throw an exception (it only does if the channel is closed), but rather it will returnfalse
if no balancingreceive
has been invoked on theRendezvousChannel
after your initialsend
. This is becauseoffer
tries to immediately add the element to the channel if it doesn't violate its capacity restrictions.