Is Kotlin's channelFlow a superset of flow?

450 Views Asked by At

We know that channelFlow can do what flow can't e.g.

It looks like it is more powerful than flow. I wonder

  • if there's anything where flow can do but not in channelFlow, or
  • if there's anything flow is preferred over channelFlow (e.g. in terms of efficiency or performance?)?

The reason I ask is, I want to see if we can just use channelFlow for everything instead, or what's the scenario we should use flow instead?

1

There are 1 best solutions below

2
On

I don't have an authoritative source, but there are two things I notice by browsing the documentation and source code.

  1. flow is lighter-weight since it doesn't have the thread-safety features of a Channel.
  2. channelFlow is buffered, but you can modify the buffer or make it RENDEVOUS with the buffer() operator. flow is not buffered, but you can use the buffer() operator, which wraps it in a Channel-based flow.

Personally, flow is my default choice for simplicity, unless the features of a Channel are needed. Frequently my cold flows are shared into a SharedFlow somewhere downstream, so I tend to avoid messing with buffering in the upstream. It all depends on where buffering behavior is best encapsulated on a case-by-case basis, though.