What is the hot flow and cold flow in coroutines and the difference between them?

Viewed 10987

I am mastering Kotlin coroutines and trying to figure out

1- what is hot flow and cold flow ?

2- what is the main difference between them?

3- when to use each one?

5 Answers

Form Here (+)

Cold vs Hot streams

Well, I really struggled with this concept because it is a little bit tricky. The main difference between cold and hot happened to be pretty simple: Hot streams produce when you don’t care while in cold streams, if you don’t collect() (or RxJava-s equivalent subscribe()) the stream won’t be activated at all. So, Flows are what we call cold streams. Removing the subscriber will not produce data at all, making the Flows one of the most sophisticated asynchronous stream API ever (in the JVM world).

Cold flow is what you need if the flow needs a collector. Each collector has its own instance of the underlying cold flow. It gets collected and it's done & gone.

Hot flow, on the other hand, does not really care too much about if it's being collected or not at that very moment. It's always around (in memory) and publishes application events emitted from possibly multiple coroutines. When some parties interested in, they get subscribed by collect, and all will get the same event (or set of events) emitted from that hot flow. Much like an event bus.

Unlike cold flows, hot flows are always in memory even tho when there's no subscribers/collectors and they're active by default. Cold flows are lazy.. However, hot flows are better for sharing a state across multiple observers.

Cold Flow:

A flow is called "cold" because every time a terminal operator is called on the flow (ex. collect) it needs to execute the producer code.

Hot Flow:

On the other hand, a "hot" flow doesn't need to execute any code when it's collected because holds the latest state in memory.

Also, cold flows only emit when there's a collector while hot flows don't care about it and always emit.

  1. Cold flows are created on-demand and emit data when they’re being observed. Hot flows are always active and can emit data regardless of whether or not they’re being observed.

  2. The main difference is that a cold flow is a type of flow that executes the producer block of code on-demand when a new subscriber collects. A hot flow is always active.

  3. See examples of usage in Manuel Vivo's articles from "Google Android developers" group:

Related