https://kotlinlang.org logo
#coroutines
Title
# coroutines
z

zjuhasz

08/14/2019, 12:55 AM
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

serebit

08/14/2019, 12:58 AM
In my own project, I decided to continue using channels, but only consume them using flows. It's worked pretty well.
z

zjuhasz

08/14/2019, 1:01 AM
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

Pablichjenkov

08/14/2019, 1:20 AM
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

Dominaezzz

08/14/2019, 1:20 AM
For me, it's more of an eager vs lazy thing. (and that ^)
p

Pablichjenkov

08/14/2019, 1:22 AM
Right hot vs cold
d

Dominaezzz

08/14/2019, 1:22 AM
That too.....ish.
g

gildor

08/14/2019, 1:47 AM
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

zjuhasz

08/14/2019, 2:06 AM
Thanks for the feedback everyone! I’ll try migrating the public API to Flows and see how it looks.
z

Zach Klippenstein (he/him) [MOD]

08/14/2019, 6:07 PM
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
4 Views