Kotlin Flow Fundamentals
A Flow<T> represents a cold, asynchronous stream that can emit multiple values sequentially over time, as opposed to a suspend function which produces exactly one value. Flows are cold, meaning the code inside a flow builder does not run until a collector calls collect — each new collector triggers its own independent execution of the producing code, unlike a hot stream (like StateFlow) which runs regardless of whether anyone is listening. Flow is built directly on coroutines, so it inherits structured concurrency: a flow collected inside a viewModelScope.launch block is automatically cancelled when that scope is cancelled.
Cricket analogy: A Flow is like a ball-by-ball radio commentary that only starts describing the over once a listener tunes in, and each new listener gets their own fresh commentary from ball one, unlike a live TV broadcast (a hot stream) that keeps running whether anyone's watching or not.
Flows are commonly produced by Room (a DAO query returning Flow<List<Entity>> automatically re-emits whenever the underlying table changes) and consumed by ViewModels to build reactive UI state. The basic building blocks are a producer (flow { emit(value) }, or automatically from Room/DataStore), zero or more intermediate operators that transform the stream, and a terminal operator like collect that actually starts execution and consumes values.
Cricket analogy: Room re-emitting on table changes is like a stadium scoreboard automatically updating the moment a run is scored, without anyone manually refreshing it, while the ViewModel is the commentator translating raw scoreboard changes into a story for the audience.
Common Operators
map transforms each emitted value; filter drops values that don't match a predicate; combine merges the latest values from multiple flows whenever any of them emits; flatMapLatest cancels the previous inner flow and switches to a new one whenever the source emits (useful for search-as-you-type, where each new query should cancel the in-flight previous search); debounce waits for a pause in emissions before propagating the latest value, also useful for search input; catch intercepts upstream exceptions without terminating collection of the whole pipeline; onEach performs a side effect per emission without altering the stream.
Cricket analogy: map is converting raw ball data into runs scored, filter drops dot balls from a highlights reel, combine merges live scores from two simultaneous matches on a multi-game screen, flatMapLatest cancels a stale run-chase projection and starts a fresh one on each new ball, and debounce waits for a batsman's shot selection to settle before updating a commentary graphic.
class SearchViewModel(private val repository: SearchRepository) : ViewModel() {
private val query = MutableStateFlow("")
val results: StateFlow<List<SearchResult>> = query
.debounce(300)
.filter { it.length >= 2 }
.distinctUntilChanged()
.flatMapLatest { text ->
repository.search(text)
.catch { emit(emptyList()) }
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = emptyList()
)
fun onQueryChanged(text: String) {
query.value = text
}
}
// Room DAO
@Dao
interface SearchDao {
@Query("SELECT * FROM results WHERE title LIKE '%' || :text || '%'")
fun search(text: String): Flow<List<SearchResult>>
}Cold vs. Hot Streams
A plain Flow is cold — its producer block runs independently for every collector, and if nobody collects, nothing happens at all. StateFlow and SharedFlow are hot streams: they exist and can emit values regardless of whether there are active collectors, and multiple collectors share the same running upstream instead of triggering it multiple times. Converting a cold Flow into a hot StateFlow with the stateIn operator is a common pattern for exposing a Room query or a repository stream as ViewModel UI state that multiple composables (or configuration changes) can subscribe to without re-running the underlying query each time.
Cricket analogy: A plain Flow is like a specific commentator's private notes that only get written if someone asks him directly, while StateFlow/SharedFlow are like the stadium's public scoreboard broadcast that runs regardless of who's watching, and stateIn turns a one-off ball-tracking calculation into that shared live scoreboard everyone in the stands reads.
Think of a cold Flow like a video you press play on privately — every viewer who presses play starts their own private screening from the beginning. A hot StateFlow is more like a live broadcast — it's playing whether or not anyone's watching, and everyone who tunes in sees the same current frame.
Collecting a cold Flow multiple times (e.g. once per recomposition without hoisting it into remembered state, or twice by accident in different composables) can trigger the producer's side effects multiple times — for instance re-running an expensive Room query or re-opening a network connection. Prefer converting shared flows to StateFlow via stateIn at the ViewModel layer rather than collecting the same cold Flow from multiple UI locations.
- Flow<T> is a cold, coroutine-based asynchronous stream that can emit multiple values sequentially over time.
- Cold flows only run their producer code when collected; each collector triggers an independent execution.
- Operators like map, filter, combine, flatMapLatest, and debounce transform or combine flows declaratively.
- Room DAO queries can return Flow<T> that automatically re-emits when the underlying table changes.
- stateIn converts a cold Flow into a hot, shared StateFlow suitable for ViewModel UI state.
- Collecting the same cold Flow from multiple places can re-trigger expensive producer work; prefer a shared hot stream instead.
Practice what you learned
1. What does it mean for a Flow to be 'cold'?
2. Which operator would you use to ensure that only the most recent search query's results are used, cancelling any prior in-flight search?
3. What is the purpose of the stateIn operator?
4. What is a key difference between a cold Flow and a StateFlow?
5. Why does a Room DAO function commonly return Flow<List<Entity>> instead of a plain suspend function?
Was this page helpful?
You May Also Like
stateIn and shareIn
stateIn and shareIn convert cold Flows into hot, shareable StateFlow and SharedFlow instances, with SharingStarted policies controlling exactly when the underlying producer runs.
Coroutines Basics in Android
Kotlin coroutines provide a lightweight, structured way to write asynchronous, non-blocking code on Android using suspend functions, coroutine builders, dispatchers, and scopes.
Room Database Basics
Room is Jetpack's SQLite abstraction layer that provides compile-time query verification, entity mapping, and Flow-based observation for reactive Android persistence.
ViewModel Basics
What Android's ViewModel class does, how it survives configuration changes, and how to create and scope ViewModels correctly in a Compose app.