问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/62072530/kotlin-channels-usage-difference-between-send-and-offer