Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between FlatMapMerge, FlatMapConcat and FlatMapLatest?

I'm having trouble differentiating the exact difference between these three operators.

The documentation for:

  • FlatMapMerge
  • FlatMapConcat
  • FlatMapLatest

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.

like image 959
Jacques.S Avatar asked Jul 09 '20 07:07

Jacques.S


1 Answers

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.

like image 176
Jacques.S Avatar answered Oct 06 '22 04:10

Jacques.S