Channels ‐ About - devrath/KotlinAlchemy GitHub Wiki
𝙲𝙾𝙽𝚃𝙴𝙽𝚃𝚂 |
|---|
What are kotlin channels |
Why channels? |
How data are sent and received |
Channels are hot |
Good use case to use Channels |
- Channels are used for asynchronous communication between the coroutines.
- Channel can be imagined as a pipe where you can add the data from one end and get the data from another end.
- Channels are lower level to flows and flows are built on top of channels.
- We can send values to channels and we can retrieve values from channels.
- We can send and receive more than one value from channels.
-
Channelsare blocking, meaning when one item sent to the channel is received from another end, THe send call is blocked until it is received from the other end. conversely, the receive call blocks until the send call is sent to the channel.
- We already know that, when we use an
asyncco-routine builder, It returns adeferredobject. So we communicated between 2 co-routines. - This is very limited Because we call an
asyncblock and wait for it to return a piece of data. It's just a1-to-1mechanism. - Channels are a more generalized way of communication where we can not only do
1-to-1,1-to-n,n-to-1, andn-to-ncommunication patterns.
- Elements in the channel are processed in the same order as they arrive in.
- There can be multiple
producersthat send the data to the channel and there can be multipleconsumersthat receive the data from the channel but on the receiving side among all the data received one of the consumers will receive it meaning the messages sent in channels are handled only once on the receiving side.
- Say, there is a
producersending emissions and there is aconsumerwho is consuming emissions. - If the consumer has already consumed emissions and a new consumer joins the consumption process, Earlier emissions that are already sent to the earlier consumer are not sent again to the new consumer, Meaning some emissions are lost for the new consumer.
- If there is a single subscriber and you want the events to be processed only once, the channels can be a good example
- Consider a chat application
- Consider a chat application, Where we
send/receivemessages back and forth from user to server and from server back to user. We can use 2 different channels to perform this operation thus making your code more readable and maintainable by separating concerns. - Channels help in explicit communication between 2 parts of the application without explicit callbacks and threading.
- Consider a chat application, Where we
