Flow basics: cold streams
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
flowOnaffect 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:
| Feature | Cold flow behaviour |
|---|---|
| Execution | Starts only when a terminal operator such as collect runs |
| Producers | One separate run of the block per collector |
| State | Nothing is shared between collectors |
| Pacing | Sequential by default: emit suspends until the collector has handled the value |
| Context | Runs 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.
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,toListandlaunchInstart the flow. Intermediate operators such asmapandfilteronly return a new cold flow. - Every new collector triggers a fresh run of the flow block.
collectis a suspend function that returns only when the flow completes, so code after it in the same coroutine waits. Collect endless flows in their ownlaunch.first()andtake(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
Flowqueries and other library flows are already main-safe; you do not needflowOnfor them. - The producer runs in the collector's coroutine, so cancelling the collector cancels the producer.
emitinflow { }checks for cancellation. - To share one run between several collectors, convert it to a hot flow with
stateInorshareIn.
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
getNumbersfunction returns a flow definition but does not run it. - The
printlninside theflowblock 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
- 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.
- 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.
- A release crashed with
IllegalStateException: Flow invariant is violatedas 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
emitinsidewithContextbreaks that rule.
- 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 aninitblock, runs at once, not per collection, so you lose the on-demand behaviour. - Expecting flowOn to change the collector's thread.
flowOnaffects only the operators above it. Thecollectblock keeps running in the collector's context. - Emitting from inside withContext.
withContext(Dispatchers.IO) { emit(x) }insideflow { }throwsIllegalStateExceptionat runtime. UseflowOn. - Putting code after collect of an endless flow. A Room query flow never completes, so a second
collectafter it in the same coroutine never runs. Start each collection in its ownlaunch. - Collecting from the UI without lifecycle awareness.
lifecycleScope.launch { flow.collect { } }keeps collecting while the app is in the background. UsecollectAsStateWithLifecycle()in Compose orrepeatOnLifecycle(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
- Create a class
SensorRepository. - Inside it, create a function
getTemperature(): Flow<Int>. - The function should use the
flow { ... }builder. - Inside the builder, use a
forloop to emit numbers from 20 to 25. - Add a
delay(500)between each emission to simulate a real sensor. - In your
mainfunction, create an instance of the repository. - Collect the flow and print: "Temp: $value".
- 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.