Flow Operators Interview Questions
KOTLIN › Flow
What is the difference between map, filter and transform on a Flow?
What a strong answer covers: map turns each value into one other value, filter keeps only values matching a predicate, and transform is the general version: for each upstream value you can emit zero, one or many values, of any type. map and filter are built on transform.
Explain flatMapLatest, flatMapConcat and flatMapMerge. Which would you use for a search box?
What a strong answer covers: All map each value to a new flow and flatten. flatMapConcat waits for each inner flow to finish before the next (ordered, sequential). flatMapMerge collects inner flows concurrently and interleaves results. flatMapLatest cancels the previous inner flow when a new value arrives. For search, flatMapLatest: a new query cancels the outdated request, usually after debounce and distinctUntilChanged.
What is the difference between combine and zip?
What a strong answer covers: zip pairs values one-to-one by position: the first of each, then the second of each, and waits for both; it stops when either ends. combine emits whenever any source emits, using the latest value from each (after all have emitted at least once). For UI state built from several sources, combine is almost always right.
How would you implement a search-as-you-type feature with Flow? Which operators and in what order?
What a strong answer covers: queryFlow.debounce(300).map { it.trim() }.distinctUntilChanged().filter { it.length >= 2 }.flatMapLatest { q -> repo.search(q).catch { emit(error state) } }.stateIn(viewModelScope, WhileSubscribed(5000), initial). Debounce limits requests while typing, distinctUntilChanged avoids duplicate searches, flatMapLatest cancels stale requests, catch inside the inner flow keeps the outer flow alive after one failure.
When does combine with several flows cause problems, such as missing initial values, glitchy intermediate states, or too many recomputations, and how do you mitigate them?
What a strong answer covers: combine waits until every source has emitted once, so one silent source means no UI state ever; give sources initial values (StateFlow or onStart). When two sources update together you get an intermediate emission with one new and one old value, which can flash an inconsistent state; derive both from one source or debounce. Every emission recomputes the whole state, so keep the lambda cheap and add distinctUntilChanged. More than five flows needs the array overload or nested combines.