Flow operators
Why it matters
- Using
flatMapMergeor plainmapwhereflatMapLatestormapLatestis needed lets a slow, stale request finish after a newer one and overwrite the screen. - A missing or badly sized
debounceeither fires a request per keystroke or makes the UI feel laggy. - Where you put
catchandflowOnchanges what they cover. Getting it wrong ends a stream after one error or runs heavy work on the main thread. - Interviewers use these operators to check that you understand sequential suspension versus cancellation of the previous work.
The simple explanation
- A water filtration system.
filteris a mesh that only lets specific sized particles through.mapis a chemical process that changes the color of the water.debounceis a valve that only opens after the water pressure has been steady for a moment.bufferis a tank that holds water so the tap doesn't run dry if the source is slow.
Flow operators are functions that transform a stream of data. They are divided into intermediate operators (which return a new Flow) and terminal operators such as collect, first or toList (which start the collection and suspend until it ends).
Intermediate operators on a cold flow are lazy; they do nothing until a terminal operator is called. A common source of bugs is the difference between the plain operators and the 'Latest' variants. map suspends on each value in turn: the next value waits until the previous transform is done. mapLatest, flatMapLatest and the terminal collectLatest run the block for each value in a child coroutine, and if a new value arrives before the block finishes, that block is cancelled.
| Operator | Type | Behavior |
|---|---|---|
map | Transformation | Applies a suspending function to every element, one at a time, in order. |
filter | Filtering | Only emits elements that match a predicate. |
debounce | Timing | Emits a value only if no newer value arrives within the timeout. The latest value is always emitted when the upstream completes. |
distinctUntilChanged | Filtering | Skips an element that is equal (==) to the previous one. |
mapLatest | Transformation | Like map, but cancels the transform still running for the previous value. |
flatMapLatest | Transformation | Maps each value to a new flow and cancels the collection of the previous inner flow when a new value arrives. |
combine | Combining | Emits whenever either flow emits, using the latest value of each (after both have emitted once). |
zip | Combining | Pairs the 1st with the 1st, the 2nd with the 2nd, and so on. Ends when either flow ends. |
flowOn | Context | Changes the CoroutineContext (usually the dispatcher) for the operators upstream of it. |
flowOn only affects the operators above it in the chain, up to the previous flowOn. The collector keeps its own context. Try the simulator below to see how the timing operators change the stream.
A user types “kotlin” into a search box. Pick an operator and compare the two lines.
queryFlow.debounce(300)A value is passed on only after 300 ms with no newer value. Fast typing collapses into the last value, delivered late.
Left to right is time, 0 to 1.6 seconds.
Notes
- Intermediate operators are lazy and only execute when collected.
flowOnchanges the context of the upstream flow, not the downstream or the collector.debounceis the usual tool for search fields: it waits for a pause in typing before passing the query on.distinctUntilChangedafterdebounceskips a request when the debounced query equals the last one. AStateFlowis already distinct byequals, so applying it directly to aStateFlowdoes nothing (the compiler reports it as a deprecated error).flatMapLatestis the usual choice for switching to a new data source when a key (query, user id, filter) changes.mapLatestcancels an expensive computation when a new value makes it stale. Use plainmapwhen every value must be processed.debounceis marked@FlowPreview, andmapLatestandflatMapLatestare@ExperimentalCoroutinesApi, so they need an@OptInto avoid a compiler warning.catchhandles exceptions from upstream only, and the flow completes after it. It does not catch exceptions thrown insidecollect.- Put
catchinsideflatMapLatest(on the inner flow) if one failed request must not end the whole stream.
Code example
A search ViewModel: trim the text, wait for a pause, skip repeats, cancel a stale request, and keep the stream alive when one request fails.
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.*
interface SearchRepository {
suspend fun search(query: String): List<String> // main-safe
}
@OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class)
class SearchViewModel(private val repository: SearchRepository) : ViewModel() {
private val query = MutableStateFlow("")
val results: StateFlow<List<String>> = query
.map { it.trim() }
.debounce(300)
.distinctUntilChanged()
.flatMapLatest { q ->
if (q.length < 3) {
flowOf(emptyList<String>())
} else {
flow { emit(repository.search(q)) }
.catch { emit(emptyList()) } // inside: one failure does not end the search
}
}
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
fun onQueryChanged(text: String) {
query.value = text
}
}debounce(300)passes a query on only after 300 ms without a newer one, so fast typing becomes one request.flatMapLatestcovers the case debounce cannot: the user pauses, a request starts, then types again. The new query cancels the request still in flight, so its result never reaches the screen.- Short queries map to an empty list instead of being filtered out, so the old results do not stay on screen when the user clears the field.
- The
catchsits on the inner flow. If it were afterflatMapLatest, the first failed request would complete the wholeresultsflow and search would stop working.
Run the idea in plain Kotlin
The same typing as the simulator above ("k", "ko", "kot", a pause, "kot", "kotl", "kotlin"), pushed through three operators. The fake search takes 400 ms.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
// Emits at 0, 100, 200, 800, 900 and 1000 ms, then stays open until 1500 ms
val typed = flow {
emit("k"); delay(100)
emit("ko"); delay(100)
emit("kot"); delay(600)
emit("kot"); delay(100)
emit("kotl"); delay(100)
emit("kotlin"); delay(500)
}
suspend fun search(query: String): String {
delay(400)
return "results for " + query
}
@OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class)
fun main() = runBlocking {
println("debounce(300):")
typed.debounce(300).collect { println(" " + it) }
println("distinctUntilChanged():")
typed.distinctUntilChanged().collect { println(" " + it) }
println("mapLatest { search(it) }:")
typed.mapLatest { search(it) }.collect { println(" " + it) }
println("zip:")
flowOf(1, 2, 3).zip(flowOf("a", "b")) { n, s -> "" + n + s }
.collect { println(" " + it) }
}Expected output:
debounce(300):
kot
kotlin
distinctUntilChanged():
k
ko
kot
kotl
kotlin
mapLatest { search(it) }:
results for kot
results for kotlin
zip:
1a
2b
debouncelets through "kot" (300 ms of quiet after 200 ms) and "kotlin". The second "kot" at 800 ms is followed by "kotl" 100 ms later, so it is dropped.mapLateststarts six searches and cancels four. Only "kot" (600 ms of quiet) and "kotlin" get the 400 ms they need.zipstops when the shorter flow ends, so3is never paired.
In production
- Users typing quickly in a search bar caused a spike in 429 Too Many Requests errors.
- The query flow called the API from
mapLatestwith nodebounce. Each keystroke cancelled the previous coroutine, but the HTTP request had already been sent, so the backend still received one request per character.
- Added
debounce(300)before the request, so only a query that survives a pause is sent. - Added
distinctUntilChanged()after it, so typing a character and deleting it within the window does not resend the same query. - Added a minimum query length and a test with a
TestDispatcherthat types five characters quickly and asserts one request.
- Users saw old search results appear after they had already typed a new query.
- Cause:
flatMapMergecollects inner flows concurrently, so a slow request for an old query could finish after the newer one and overwrite its results.
- Replaced
flatMapMergewithflatMapLatest. - Now, when a new query passes the debounce, the request for the previous query is cancelled, and a cancelled request never emits.
Common mistakes
- Using map for slow work where only the latest value matters.
mapprocesses every value in turn, so stale work keeps running and delays newer values. UsemapLatest(orflatMapLatest) when an old result is useless once a new value arrives. - Putting flowOn before the heavy operators.
flowOnonly affects what is above it. Insource.flowOn(Dispatchers.Default).map { parse(it) },parsestill runs in the collector's context. PutflowOnbelow the heavy work. - Adding distinctUntilChanged right after a StateFlow. A
StateFlowalready skips values equal to the current one, so it has no effect, and the compiler flags it. It is useful after operators likemapordebounce, where equal values can appear again. - Putting catch after flatMapLatest in a long-lived stream. The first error completes the whole flow and the screen stops updating. Catch on the inner flow, or use
retry/retryWhenif the source should be restarted. - Using runCatching inside a flow or collector. It also catches
CancellationException, so cancellation is swallowed. Use thecatchoperator, or rethrowCancellationException.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is the difference between map and mapLatest?”
“How does flowOn work?”
“What is the difference between flatMapMerge and flatMapLatest?”
“How do you handle errors in a Flow?”
Quiz
Which operator should you use to avoid calling a search API for every single character typed?
In flow.map { a(it) }.flowOn(Dispatchers.IO).map { b(it) }.collect { c(it) }, which calls run on Dispatchers.IO?
What happens to a mapLatest block that is still running when the upstream emits a new value?
Flow A emits 1, 2, 3 and flow B emits "a", "b", both immediately. What does A.zip(B) emit?
0 of 4 answered
Mini task
Task: The Search Optimization Challenge
Goal: Create a flow that turns raw user input into cleaned, debounced and unique search terms.
- Create a
MutableStateFlow<String>that acts as a source of raw user input. - Create a
Flow<String>that applies the following logic, in this order:- Removes leading and trailing whitespace using
map. - Ignores any strings that are shorter than 3 characters using
filter. - Waits for 500 ms of inactivity using
debounce. - Ensures that if the user types 'apple', then 'apple' again, it only emits once using
distinctUntilChanged.
- Removes leading and trailing whitespace using
- In
runBlocking,launcha coroutine that collects the flow and prints each result. - Set the input to
" apple ","apple","ap","apple"and"orange", withdelay(600)after each one. Then cancel the collecting job (aStateFlownever completes on its own).
Done Condition: The console prints only apple and orange. Then remove the delays and explain why only orange is printed.