Flow basics: cold streams

Learn Kotlin Flow basics and the difference between cold and hot streams in Android to optimize resource usage and master asynchronous data lifecycles. About 20 minutes.

Why it matters

  • Prevents accidental resource leaks by ensuring work only happens during collection.
  • Avoids unnecessary CPU/battery usage by not running logic when no UI is listening.
  • Interviewers use 'cold vs hot' to test if you understand the lifecycle of asynchronous data.
  • Crucial for understanding how operators like flowOn affect execution context.

The simple explanation

  • A YouTube video is a cold stream.
  • The video does not play until you click 'Play'.
  • If two people click 'Play' at different times, they both see the video from the start.
  • Each viewer gets their own independent execution of the video content.

A Flow is a cold stream. This means the code inside a flow { ... } builder does not execute until a terminal operator (like collect) is called.

When you call collect, the flow block starts running in the collector's coroutine. If you collect the same flow instance twice, the block runs twice from the beginning. This is different from StateFlow and SharedFlow (hot flows), which hold or broadcast values whether or not anyone is collecting.

Key characteristics of cold flows:

FeatureCold flow behaviour
ExecutionStarts only when a terminal operator such as collect runs
ProducersOne separate run of the block per collector
StateNothing is shared between collectors
PacingSequential by default: emit suspends until the collector has handled the value
ContextRuns in the collector's coroutine context unless you use flowOn

By default the producer runs on the collector's dispatcher. To move it, use flowOn(Dispatchers.IO): it changes the context of everything upstream of it, while the collector stays where it is. Do not wrap emit in withContext inside flow { }. A flow must emit in the same context it was collected in, and breaking that rule throws IllegalStateException: Flow invariant is violated.

A cold flow runs once per collector
A cold flow runs once per collector A flow is created and nothing runs. Collector 1 calls collect, and the flow block runs and emits values to it. Collector 2 then calls collect, and the block runs again from the start, separately, emitting its own values to collector 2. Created, nothing runs yet Each collector gets its own run collect() RUNS: 1, 2, 3 collect() RUNS AGAIN: 1, 2, 3 Collector 1 first caller flow { } the block Collector 2 second caller
Creating the flow runs nothing. Each collect call starts its own fresh run of the flow block.

Notes

  • A cold flow is a blueprint, not a running process. Code inside flow { ... } does not run when the flow is created.
  • Terminal operators such as collect, first, toList and launchIn start the flow. Intermediate operators such as map and filter only return a new cold flow.
  • Every new collector triggers a fresh run of the flow block.
  • collect is a suspend function that returns only when the flow completes, so code after it in the same coroutine waits. Collect endless flows in their own launch.
  • first() and take(n) stop the producer early by cancelling it once they have enough values.
  • Use flowOn(Dispatchers.IO) to move blocking producer work. It affects only operators above it.
  • Room Flow queries and other library flows are already main-safe; you do not need flowOn for them.
  • The producer runs in the collector's coroutine, so cancelling the collector cancels the producer. emit in flow { } checks for cancellation.
  • To share one run between several collectors, convert it to a hot flow with stateIn or shareIn.

Code example

This example demonstrates how a cold flow restarts its logic for every new collector.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
 
class DataRepository {
    // This is a cold flow
    fun getNumbers(): Flow<Int> = flow {
        println("Starting flow production...")
        for (i in 1..3) {
            delay(100)
            emit(i)
        }
    }
}
 
suspend fun main() {
    val repository = DataRepository()
    val numberFlow = repository.getNumbers()
 
    println("Collector 1 starting")
    numberFlow.collect { value ->
        println("Collector 1 received: " + value)
    }
 
    println("Collector 2 starting")
    numberFlow.collect { value ->
        println("Collector 2 received: " + value)
    }
}
  • The getNumbers function returns a flow definition but does not run it.
  • The println inside the flow block shows that the producer runs separately for each collector.

Run the idea in plain Kotlin

Nothing runs at creation, each collector starts the producer again, emissions and collection take turns, and first() stops the producer after one value.

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking

fun numbers(): Flow<Int> = flow {
  println("  producer starts")
  for (i in 1..3) {
      delay(100)
      println("  emit " + i)
      emit(i)
  }
}

fun main() = runBlocking {
  val flow = numbers()
  println("flow created, nothing has run yet")

  println("collector 1")
  flow.collect { println("  got " + it) }

  println("collector 2 takes only the first value")
  val first = flow.first()
  println("  first = " + first)
}

Expected output:

flow created, nothing has run yet
collector 1
  producer starts
  emit 1
  got 1
  emit 2
  got 2
  emit 3
  got 3
collector 2 takes only the first value
  producer starts
  emit 1
  first = 1

In production

Every screen open made two network calls
  • Backend logs showed exactly twice the expected requests to the profile endpoint.
  • The ViewModel exposed val profile: Flow<Profile> = flow { emit(api.getProfile()) }.
  • The screen collected it twice, once for the header and once for the settings section, so each collector ran the request again.
The fix
  • Converted it in the ViewModel with stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null), so all collectors share one upstream run.
  • The 5-second timeout keeps the upstream alive through a configuration change instead of restarting it.
  • Request counts dropped back to one per screen open.
Crash: Flow invariant is violated
  • A release crashed with IllegalStateException: Flow invariant is violated as soon as the file list screen opened.
  • The repository did flow { withContext(Dispatchers.IO) { emit(readFiles()) } } to keep disk work off the main thread.
  • A flow must emit in the collector's context, and emit inside withContext breaks that rule.
The fix
  • Rewrote it as flow { emit(readFiles()) }.flowOn(Dispatchers.IO).
  • The file reading runs on IO, and the collector still receives values on the main thread.
  • Added a unit test that collects the flow, which would have caught the crash before release.

Common mistakes

  • Assuming a flow is running before collection. Calling repository.observeItems().map { ... } without a terminal operator does nothing, and nothing warns you.
  • Doing the work outside the flow block. Code in a function body before return flow { }, or in an init block, runs at once, not per collection, so you lose the on-demand behaviour.
  • Expecting flowOn to change the collector's thread. flowOn affects only the operators above it. The collect block keeps running in the collector's context.
  • Emitting from inside withContext. withContext(Dispatchers.IO) { emit(x) } inside flow { } throws IllegalStateException at runtime. Use flowOn.
  • Putting code after collect of an endless flow. A Room query flow never completes, so a second collect after it in the same coroutine never runs. Start each collection in its own launch.
  • Collecting from the UI without lifecycle awareness. lifecycleScope.launch { flow.collect { } } keeps collecting while the app is in the background. Use collectAsStateWithLifecycle() in Compose or repeatOnLifecycle(Lifecycle.State.STARTED) with Views.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between a cold stream and a hot stream?”

“If I collect a cold flow twice, how many times does the code inside the flow { ... } block run?”

“How do you ensure a flow performs its work on a background thread?”

“What happens to a cold flow if the coroutine collecting it is cancelled?”

Quiz

Which of the following is a characteristic of a cold flow?

Inside flow { }, a repository calls withContext(Dispatchers.IO) { emit(readFile()) }. What happens?

Which operator is used to change the context of the code upstream of the operator?

Two coroutines collect the same cold flow at the same time. How many times does the flow { } block run?

0 of 4 answered

Mini task

Task: Create a Custom Cold Flow

  1. Create a class SensorRepository.
  2. Inside it, create a function getTemperature(): Flow<Int>.
  3. The function should use the flow { ... } builder.
  4. Inside the builder, use a for loop to emit numbers from 20 to 25.
  5. Add a delay(500) between each emission to simulate a real sensor.
  6. In your main function, create an instance of the repository.
  7. Collect the flow and print: "Temp: $value".
  8. Done Condition: When you run the code, you should see the temperatures printed one by one with a half-second pause between each, and the program should exit after the last value.
Next: StateFlow and SharedFlow