I’m trying to decide between a `Channel` or `Flow`...
# coroutines
z
I’m trying to decide between a
Channel
or
Flow
based API for my library and I’m having a hard time. I’m looking for some info / opinions / suggestions. I posted on the forum with all the info: https://discuss.kotlinlang.org/t/deciding-between-flows-and-channels/13858
s
In my own project, I decided to continue using channels, but only consume them using flows. It's worked pretty well.
z
The problem is I’m making a library and going between channels and flows can go several levels deep. So if I choose to expose channels in the api I’ll have to go
Channel
->
Flow
->
Channel
which defeats the purpose of why I’m consider flows which is primarily to avoid launching a coroutine for these intermediate steps.
p
I think if you plan to do a lot of unidirectional operations, reactive stream oriented style you should go with Flow. Something that goes from a single source -> single sink kind of problem, Flow fits there too. Channels fits better when there is bidirectional interaction with the API. Message driven, Actor style, multiple producers -> one consumer type of thing. In reality both can be mixed.
d
For me, it's more of an eager vs lazy thing. (and that ^)
p
Right hot vs cold
d
That too.....ish.
g
Definitely Flow for library public API
For me, it’s more of an eager vs lazy thing. (and that ^) (edited)
That is the point! Flow may be lazy and eager or cold and hot depending on implementation, channel is always eager and hot The main thing that Flow is more universal primitive, more safe (no need to expose any resources management mechanisms, or ask user of your API to close channel etc) and just easy to use by consumer of your API
💯 2
z
Thanks for the feedback everyone! I’ll try migrating the public API to Flows and see how it looks.
z
Also note that most Flow builders and operators that use channels will fuse together and share a single channel, as long as there are no other operators (e.g.
map
) between them. E.g.
channelFlow
,
BroadcastChannel.asFlow
,
produceIn
,
buffer
,
flowOn
👍 1