sarmad sohaib
05/19/2023, 3:13 PMCasey Brooks
05/19/2023, 3:35 PMflatMapConcat
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.
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
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"...]
sarmad sohaib
05/19/2023, 3:38 PMCasey Brooks
05/19/2023, 3:45 PMFlow
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.