Flow operators

Learn intermediate Kotlin Flow operators for Android to transform, filter, combine, and control data streams while mastering timing and cancellation. About 25 minutes.

Why it matters

  • Using flatMapMerge or plain map where flatMapLatest or mapLatest is needed lets a slow, stale request finish after a newer one and overwrite the screen.
  • A missing or badly sized debounce either fires a request per keystroke or makes the UI feel laggy.
  • Where you put catch and flowOn changes 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.
  • filter is a mesh that only lets specific sized particles through.
  • map is a chemical process that changes the color of the water.
  • debounce is a valve that only opens after the water pressure has been steady for a moment.
  • buffer is 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.

OperatorTypeBehavior
mapTransformationApplies a suspending function to every element, one at a time, in order.
filterFilteringOnly emits elements that match a predicate.
debounceTimingEmits a value only if no newer value arrives within the timeout. The latest value is always emitted when the upstream completes.
distinctUntilChangedFilteringSkips an element that is equal (==) to the previous one.
mapLatestTransformationLike map, but cancels the transform still running for the previous value.
flatMapLatestTransformationMaps each value to a new flow and cancels the collection of the previous inner flow when a new value arrives.
combineCombiningEmits whenever either flow emits, using the latest value of each (after both have emitted once).
zipCombiningPairs the 1st with the 1st, the 2nd with the 2nd, and so on. Ends when either flow ends.
flowOnContextChanges 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.

Try it: what reaches the collector?

A user types “kotlin” into a search box. Pick an operator and compare the two lines.

queryFlow.debounce(300)
typed (upstream)
kkokotkotkotlkotlin
collected (downstream)
kotkotlin

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.
  • flowOn changes the context of the upstream flow, not the downstream or the collector.
  • debounce is the usual tool for search fields: it waits for a pause in typing before passing the query on.
  • distinctUntilChanged after debounce skips a request when the debounced query equals the last one. A StateFlow is already distinct by equals, so applying it directly to a StateFlow does nothing (the compiler reports it as a deprecated error).
  • flatMapLatest is the usual choice for switching to a new data source when a key (query, user id, filter) changes.
  • mapLatest cancels an expensive computation when a new value makes it stale. Use plain map when every value must be processed.
  • debounce is marked @FlowPreview, and mapLatest and flatMapLatest are @ExperimentalCoroutinesApi, so they need an @OptIn to avoid a compiler warning.
  • catch handles exceptions from upstream only, and the flow completes after it. It does not catch exceptions thrown inside collect.
  • Put catch inside flatMapLatest (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.
  • flatMapLatest covers 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 catch sits on the inner flow. If it were after flatMapLatest, the first failed request would complete the whole results flow 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
  • debounce lets 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.
  • mapLatest starts six searches and cancels four. Only "kot" (600 ms of quiet) and "kotlin" get the 400 ms they need.
  • zip stops when the shorter flow ends, so 3 is never paired.

In production

The Rapid-Fire API Crash
  • Users typing quickly in a search bar caused a spike in 429 Too Many Requests errors.
  • The query flow called the API from mapLatest with no debounce. Each keystroke cancelled the previous coroutine, but the HTTP request had already been sent, so the backend still received one request per character.
The fix
  • 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 TestDispatcher that types five characters quickly and asserts one request.
The Ghost Result Bug
  • Users saw old search results appear after they had already typed a new query.
  • Cause: flatMapMerge collects inner flows concurrently, so a slow request for an old query could finish after the newer one and overwrite its results.
The fix
  • Replaced flatMapMerge with flatMapLatest.
  • 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. map processes every value in turn, so stale work keeps running and delays newer values. Use mapLatest (or flatMapLatest) when an old result is useless once a new value arrives.
  • Putting flowOn before the heavy operators. flowOn only affects what is above it. In source.flowOn(Dispatchers.Default).map { parse(it) }, parse still runs in the collector's context. Put flowOn below the heavy work.
  • Adding distinctUntilChanged right after a StateFlow. A StateFlow already skips values equal to the current one, so it has no effect, and the compiler flags it. It is useful after operators like map or debounce, 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/retryWhen if the source should be restarted.
  • Using runCatching inside a flow or collector. It also catches CancellationException, so cancellation is swallowed. Use the catch operator, or rethrow CancellationException.

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.

  1. Create a MutableStateFlow<String> that acts as a source of raw user input.
  2. 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.
  3. In runBlocking, launch a coroutine that collects the flow and prints each result.
  4. Set the input to " apple ", "apple", "ap", "apple" and "orange", with delay(600) after each one. Then cancel the collecting job (a StateFlow never completes on its own).

Done Condition: The console prints only apple and orange. Then remove the delays and explain why only orange is printed.

Next: Collecting flows safely in the UI