Skip to content

Channels ‐ About

Devrath edited this page Jan 18, 2024 · 8 revisions

What are kotlin 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.
  • Channels are 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.

Why channels?

  • We already know that, when we use an async co-routine builder, It returns a deferred object. So we communicated between 2 co-routines.
  • This is very limited Because we call an async block and wait for it to return a piece of data. It's just a 1-to-1 mechanism.
  • Channels are a more generalized way of communication where we can not only do 1-to-1, 1-to-n, n-to-1, and n-to-n communication patterns.

How data are sent and received

  • Elements in the channel are processed in the same order as they arrive in.
  • There can be multiple producers that send the data to the channel and there can be multiple consumers that 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.

Channels are hot 🔥

  • Say, there is a producer sending emissions and there is a consumer who 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.

Good use case to use Channels

  • 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/receive messages 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.
Clone this wiki locally