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

Jordi Saumell

12/02/2019, 4:20 PM
I’m quite new to flows and channels and I have a question: what is the benefit of consuming a channel as a flow? My understanding from reading Roman Elizarov is that flows are cold and channels hot, so if the emitter is a channel (hot), listening to it from a flow could not make it cold (correct me if I’m wrong). Therefore, what is it used for?
s

streetsofboston

12/02/2019, 4:28 PM
Flow supports Structured Concurrency. It is almost like a
suspend fun
, but it supports the handling of more than one result.
Channels are not only hot, but you’d need to manage their lifecycles (or the lifecycles of the producers of emitted values) separately/explicitly from the Channels’ consumer.
s

serebit

12/02/2019, 4:50 PM
If I recall correctly, channels are always hot, but flows can be hot or cold depending on their source. This allows for a unified suspending collection API regardless of source temperature, which is extremely useful. (Also what Anton mentioned)
j

Jordi Saumell

12/02/2019, 5:04 PM
Thank you! Could you elaborate a bit more how the handling of the lifecycle of the channel from the flow differs?
s

streetsofboston

12/02/2019, 6:12 PM
@Jordi Saumell I wrote a blog post about this. Maybe it can help you out. https://medium.com/swlh/how-can-we-use-coroutinescopes-in-kotlin-2210695f0e89
👍 3
j

Joris PZ

12/03/2019, 10:47 PM
I find the information around Flows really confusing. Most introductions talk about cold flows and hot streams, and you should still use Channels for things like incoming network messages. But then it turns out flows can suddenly be hot too, and you can just
asFlow()
a hot Channel, and now Flows are not about cold vs hot but just a way to provide structure like coroutinescopes do, and also a unified API.
s

streetsofboston

12/04/2019, 12:21 AM
True, except the part for incoming network messages. For incoming network messages, it depends. For observing messages over web-sockets, for example, a Channel would be the first choice: Start a Thread that sends/offers messages from a socket to a Channel. Observers/consumers can receive them. Stopping the thread will close the Channel. But for BLE (Bluetooth Low Energy) scanning, you'd want to use a Flow. Since scanning is expensive, you'd want to shut it down when no one is listening. A cold stream like a Flow is perfect for this.
5 Views