Hot vs cold flows — Kotlin Coroutines

Ziyf
2 min readJul 13, 2023

--

In Kotlin, a “hot flow” refers to a type of flow that produces values regardless of whether there are active collectors.

While “cold flows,” which only emit values when there is an active collector.

But what does that really mean ??

Let’s look at an example using Flow “Cold” vs SharedFlow “hot”.

 // Regular Flow example
val coldFlow = flow {
emit(0)
emit(1)
}

launch { // Calling collect triggers the emit()
coldFlow.collect { value ->
println("cold flow collector received: $value")
}
}


// RESULT
flow collector received: [0, 1]
    // SharedFlow example
val sharedFlow = MutableSharedFlow<Int>()

sharedFlow.emit(0)

launch {
sharedFlow.collect { value ->
println("SharedFlow collector received: $value")
}
}

sharedFlow.emit(1)
sharedFlow.emit(2)

// RESULT
SharedFlow collector received: [1,2]

In the example,

Regular Flow

  1. in the beginning WILL NOT trigger any emit() as the first value, since there is no collector.
  2. Only when a new collector subscribes, it will trigger the flow’s emit(0), emit(1) hence the phrase “only emit values when there is an active collector.
  3. Any future/ new collectors will re-trigger the emit and receive [0,1] values.

SharedFlow

  1. in the beginning it emits 0 as the first value.
  2. when a new collector subscribes, it will NOT receive 0 since it only registered after.
  3. will only pick up later emissions, so [1,2] will be the result.

So to help you remember,

You can think of SharedFlow , “Hot” as an live event like twitch TV or youtube LIVE where you get what comes and unable to rewind so for “hot flows”, collecting from the flow doesn’t trigger any producer code.

While, the defaultFlow is a cold flow, and will ONLY emit data when they are being observed hence why we see the collector receive all the values past and future [0,1..]. The collector will receive the current value immediately upon subscription and then collects subsequent emissions.

So to summarise,

Emission Behavior:

  • Cold Flow: A cold flow emits values only when there is an active collector. Each collector receives the emitted values independently, and they start receiving emissions from the beginning when they subscribe.
  • Hot Flow: A hot flow emits values regardless of whether there are active collectors. It can produce values even if there are no subscribers. New collectors joining a hot flow might miss emissions that occurred before they started listening.

--

--