I'm recently studying and reading a lot about Flow and Kotlin Coroutines. But I still get confused about when I should use Flow
and when I should use Channel
.
At the beginning it looked more simple. Working with hot streams of data? Channel
. Cold ones? Flows
. Same goes if you need to listen to streams of data from more than a single place; if that's the case Channel
is the choice to go. There are still a lot of examples and questions.
But recently FlowChannels
where introduced, together with tons of methods and classes that encourage the use of Flow
, which facilities transforming Channels
into Flows
and so on. With all this new stuff coming on each Kotlin release I am getting more and more confused. So the question is:
When should I use Channel and when should I use Flow?
For many use cases where the best tool so far was Channel
, Flow
has become the new best tool.
As a specific example, callbackFlow
is now the best approach to receiving data from a 3rd-party API's callback. This works especially well in a GUI setting. It couples the callback, a channel, and the associated receiving coroutine all in the same self-contained Flow
instance. The callback is registered only while the flow is being collected. Cancellation of the flow automatically propagates into closing the channel and deregistering the callback. You just have to provide the callback-deregistering code once.
You should look at Channel
as a lower-level primitive that Flow
uses in its implementation. Consider working with it directly only after you realize Flow
doesn't fit your requirements.