I'm having trouble differentiating the exact difference between these three operators.
The documentation for:
These documentation links indicate that two Flows are flatmapped into a single Flow object. I am fine with that, but I have a hard time understanding how the emissions would change between these three operators.
I went looking through the source code and found a sensible guide that I didn't find via googling. https://kotlinlang.org/docs/reference/coroutines/flow.html#flattening-flows
The guide explains the differences but it was still a bit unclear to me, so I rewrote it in my own words here.
The basic difference between the three are determined by the way in which the inner and outer flow react to new emissions from either flow. So for the given code:
val outerFlow: Flow<>
val flatMappedFlow = outerflow
.flatMapXXXXX { innerFlow(it) }
.collect { processFlatMapResult(it) }
FlatMapConcat
This operator is sequential and paired. Once the outerFlow emits once, the innerFlow must emit once before the final result is collected. Once either flow emits a Nth time, the other flow must emit a Nth time before the Nth flatMapResult is collected.
FlatMapMerge
This operator has the least restrictions on emissions, but can result in too many emissions. Every time the outerFlow emits a value, each of the innerFlow emissions are flatMapped from that value into the final flatMapResult to be collected. The final emission count is a multiplication of innerFlow and outerFlow emissions.
FlatMapLatest
This operator cares only about the latest emitted results and does not process old emissions. Every time the outerFlow emits a value, it is flatMapped with the latest innerFlow value. Every time the innerFlow emits a value, it is flatMapped with the latest outerFlow value. Thus the final emission count is a value between zero and innerFlow emissions times outerFlow emissions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With