Kotlin
flatMapLatest
Learn latest stream with flatMapLatest.
What is flatMapLatest?
flatMapLatest starts a new flow for each upstream value; when a new value arrives it cancels the previous flow and starts the latest one. It fits scenarios focused on the most recent value, such as search suggestions.
Example: queryFlow.flatMapLatest { query -> searchFlow(query) }. If the user types fast and a new query arrives before the previous finishes, the old result is cancelled. This cuts unnecessary network calls and focuses on the latest query. Compared with flatMapMerge, here only one inner flow runs at a time.
Exercise Combine flows with flatMapLatest
Write flowOf(1, 2).flatMapLatest { value -> flowOf(value * 10) }.collect { result -> println("Result: $result") }. A new inner flow starts for each value.
Show example solution
fun main() = runBlocking {
flowOf(1, 2).flatMapLatest { value ->
flowOf(value * 10)
}.collect { result ->
println("Result: $result")
}
}
flatMapLatest vs flatMapMerge
flatMapLatest runs only one inner flow at a time; the previous is cancelled when a new value arrives. flatMapMerge starts inner flows in parallel and merges their results in a mixed order.
For search suggestions, flatMapLatest fits: while the user keeps typing, only the last query runs. For parallel data fetching, flatMapMerge is more efficient: you pull from several sources at once. flatMapConcat processes inner flows in order, never moving to the next until the previous is done. The three operators fit different needs.
Test yourself
-
What does flatMapLatest do?
- Runs all inner flows in parallel
- Processes inner flows in order
- Cancels the previous inner flow when a new value arrives
- Starts no inner flow
Show answer
Cancels the previous inner flow when a new value arrives — flatMapLatest cancels the previous inner flow when a new value arrives.
-
Match flatMapLatest parts
- flatMapLatest
- Starts inner flow
- previous inner
- Cancelled
- latest value
- Priority
- single inner
- At once
-
Complete the flatMapLatest call
flow.____ { query -> flowOf(query) }
Show answer
flow.flatMapLatest { query -> flowOf(query) }
Next lesson: Summary - Advanced Flow