Can anybody explain flatMapMerge and flatMapConcat...
# getting-started
s
Can anybody explain flatMapMerge and flatMapConcat with some real world example? I have read the docs and seen videos but they are confusing. Thanks a lot.
c
The biggest difference is that
flatMapConcat
collects the entirety of each
Flow
returned by the
transform
lambda, before starting to collect the next flow. It processes each flow in series, and thus one flow that emits slowly or runs infiniately will prevent the later ones from running.
Copy code
flow<Flow<String>> {
    emit(flowOf("one", "two", "three"))
    emit(flow {
        // this is an infinite flow
        var i = 0
        while (true) {
            i++
            emit(i.toString())
        }
    })
    emit(flowOf("ONE", "TWO", "THREE")) // will never start collecting this flow
}.flatMapConcat { it }
// result: ["one", "two", "three", "1", "2", "3", "4"...]
flatMapMerge
collects each flow in parallel. So slow/infinite emitters are not a problem
Copy code
flow<Flow<String>> {
    emit(flowOf("one", "two", "three"))
    emit(flow {
        var i = 0
        while (true) {
            i++
            emit(i.toString())
        }
    })
    emit(flowOf("five", "six", "seven"))
}.flatMapMerge { it }
// result: ["one", "1", "ONE", "two", "2", "TWO", "three", "3", "THREE", "4", "5"...]
👍 1
s
Thanks. Can you provide an easy to read and understand example?
c
What’s confusing about the examples posted above? I’m not sure how to get any simpler than that. You have a
Flow
that emits more
Flows
, then uses the
flatMapConcat
or
flatMapMerge
operators on the result. For the first snippet, using
flatMapConcat
, since the second Flow is infinite, it will never be able to start processing the third. But using
flatMapMerge
instead will run them all 3 Flows in parallel, merging each value into the resulting list.