flatMapConcat vs flatMapMerge vs flatMapLatest — Explained
Imagine you have a magical coloring book (the original flow) that can create new coloring pages (inner flows) whenever you want. You have three different ways to color these pages (operators):
1. flatMapConcat: One Page at a Time
This is like coloring one page at a time. Even if the magical book gives you a new page, you’ll finish coloring the current page before moving on to the next one. This way, you color all the pages in the exact order they were given to you.
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.delay
fun main() = runBlocking {
val originalFlow = flow {
emit(1)
delay(100)
emit(2)
delay(100)
emit(3)
}
originalFlow.flatMapConcat { value ->
flow {
emit("Page $value: Start coloring")
delay(200)
emit("Page $value: Finish coloring")
}
}.collect { result ->
println(result)
}
}
/*****
Result
Page 1: Start coloring
Page 1: Finish coloring
Page 2: Start coloring
Page 2: Finish coloring
Page 3: Start coloring
Page 3: Finish coloring
*****/
2. flatMapLatest: Always Color the Newest Page
This is like always wanting to color the newest page. If you’re coloring a page and the magical book gives you a new one, you’ll immediately leave the current page, even if it’s not finished, and start coloring the new page. This way, you only focus on the latest page given to you.
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.delay
fun main() = runBlocking {
val originalFlow = flow {
emit(1)
delay(100)
emit(2)
delay(100)
emit(3)
}
originalFlow.flatMapLatest { value ->
flow {
emit("Page $value: Start coloring")
delay(200)
emit("Page $value: Finish coloring")
}
}.collect { result ->
println(result)
}
}
/*****
Result
Page 1: Start coloring
Page 2: Start coloring
Page 3: Start coloring
Page 3: Finish coloring
*****/
3. flatMapMerge: Coloring Multiple Pages Simultaneously
This is like being able to color multiple pages at the same time. If the magical book gives you several pages, you can start coloring all of them at once, switching between pages as you wish. This way, you can work on many pages together, finishing them faster.
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.delay
fun main() = runBlocking {
val originalFlow = flow {
emit(1)
delay(100)
emit(2)
delay(100)
emit(3)
}
originalFlow.flatMapMerge(concurrency = 2) { value ->
flow {
emit("Page $value: Start coloring")
delay(200)
emit("Page $value: Finish coloring")
}
}.collect { result ->
println(result)
}
}
/*****
Result
Page 1: Start coloring
Page 2: Start coloring
Page 1: Finish coloring
Page 3: Start coloring
Page 2: Finish coloring
Page 3: Finish coloring
*****/
Thanks for reading this article. You can learn more about me from here
If you found this article helpful, please recommend it by hitting the clap icon as many times you wish 👏 Let’s enable each other with the power of knowledge.