Junior — Middle
What are the main differences between the flatMapLatest and flatMapMerge operators in reactive programming?
sobes.tech AI
Answer from AI
In reactive programming, such as Kotlin Flow, the operators flatMapLatest and flatMapMerge are used to transform stream elements into new streams but differ in behavior when new elements appear:
-
flatMapLatest: cancels the previous inner stream when a new element arrives and switches to the new one. This is useful when only the latest result matters, such as in autocomplete searches.
-
flatMapMerge: runs all inner streams in parallel and merges their results, without canceling previous ones. Used when you want to process all requests simultaneously.
Example:
flowOf(1, 2, 3)
.flatMapLatest { value -> flow {
emit(value)
delay(100)
emit(value * 10)
} }
// Only the last element (3) will be processed, previous ones canceled.
flowOf(1, 2, 3)
.flatMapMerge { value -> flow {
emit(value)
delay(100)
emit(value * 10)
} }
// All elements will be processed in parallel and merged.