Cold vs hot flows

Flow and StateFlow Junior Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Predict the output

How many times is 'start' printed?

fun main() = runBlocking {
    val numbers = flow {
        println("start")
        emit(1)
    }
    numbers.collect { }
    numbers.collect { }
}
Options
Hint 1 of 1

When does the code inside flow { } run?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Twice

Correct. A cold flow runs its block once per collector.

Why not the others?
  • B Once. That would be a shared, hot flow.
  • C Never, because nothing is printed inside collect. The flow block itself prints, and it runs when collected.
  • D Once when the flow is created, then never. Creating a flow runs nothing; collecting does.

30-second answer

A cold Flow runs its producer code again for every collector, and only while someone collects. Nothing happens until collect is called. A hot flow such as StateFlow or SharedFlow exists independently of collectors: values are emitted whether or not anyone listens, and all collectors share the same stream.

Practise saying it · 35 s. No recording, just a timer

Explain cold vs hot flows.

Say your answer out loud, then check which of these points you covered:

  • Cold runs per collector, only when collected
  • Hot exists without collectors
  • stateIn/shareIn make a flow hot
  • Hot flows never complete

Deep dive

flow { }, flowOf, Room queries and Retrofit-backed flows are cold.

Two collectors of a cold flow mean two network calls or two database queries.

stateIn and shareIn turn a cold flow into a hot one that is shared within a scope.

A hot flow never completes on its own, so collect on it suspends forever until cancelled.

Common mistakes

  • Collecting the same cold network flow from three places and making three requests.
  • Calling collect on a StateFlow and expecting the next line to run.
  • Thinking a cold flow starts when it's created.

Senior take & follow-ups

Seniors explain the cost: cold means duplicated work per collector, hot means a scope that owns the producer.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do you share one upstream between many collectors?

    Show hint

    shareIn or stateIn in a scope such as viewModelScope.

  2. Does a Room Flow query run if nobody collects?

    Show hint

    No, it's cold.

Similar on iOS: What Combine is for Combine publishers are mostly cold too, but sharing uses share() and subjects instead of stateIn.

Suggest a fix if something here is wrong or out of date.