CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

Main.kt
// Use flatMapLatest
// write here
fun main() = runBlocking {
    
}

Sample solution

Main.kt
fun main() = runBlocking {
    flowOf(1, 2).flatMapLatest { value ->
        flowOf(value * 10)
    }.collect { result ->
        println("Result: $result")
    }
}

Expected output

Result: 10
Result: 20

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.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 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 Correct answer
  • Starts no inner flow

Explanation: flatMapLatest cancels the previous inner flow when a new value arrives.

2 Match flatMapLatest parts

Term Meaning
flatMapLatest Starts inner flow
previous inner Cancelled
latest value Priority
single inner At once

3 Complete the flatMapLatest call

Question
flow.____ { query -> flowOf(query) }
Answer
flow.flatMapLatest { query -> flowOf(query) }

Explanation: flatMapLatest prioritizes the latest inner flow.

All lessons in Advanced