-
Notifications
You must be signed in to change notification settings - Fork 22
Channels and Flows ‐ When to use each of them
- Channels and Flows are both used for concurrency in kotlin co-routines.
- They both help to achieve
asynchronous behavior
.
Channels provide a low-level API compared to flows, If you need more fine-grained control over co-routines and emissions of data, the channels are a better fit.
Channels can either be buffered or can not be buffered, This allows us to control the amount of data that is being sent even before receiving data in the receiver.
Channels help in implementing complex communication patterns, Ex: Making the channel wait before multiple channels perform complex operations using the SELECT operation.
Channels have explicit support for the channel close operation(isClosedForReceive, isClosedForSend), allowing coroutines to react to the end of the communication.
Since they are built on top of the channels, They provide additional features that channels do that provide for streams of data like operators.
Using operators we can compose and react to data streams in an efficient manner. Some operators include map
,filter
,collectLatest
.
They provide mechanisms of cancellation. When a co-routine is canceled the cancellation can be propagated upstream and handled accordingly.
When the downstream collector is slower than the upstream emitters, Flow provides mechanisms of backpressure handling by avoiding overflowing buffers.
- If you need low-level control, selectivity, or explicit handling of closed channels, channels might be a better fit.
- If you prefer a higher-level, declarative, and composable API with built-in support for cancellation and backpressure, flows are a good choice.