Good morning, is there an operator for concatenati...
# coroutines
s
Good morning, is there an operator for concatenating two `Flow`s, something like:
Copy code
val flow1 = flowOf(1, 2, 3)
val flow2 = flowOf(4, 5, 6)
val flow3 = flow1.concat(flow2) // = 1, 2, 3, 4, 5, 6
The order of
flow3
does not matter here, so it also might be
1, 4, 2, 5, 3, 6
or any other order, depending on how the values are produced in
flow1
and
flow2
.
Copy code
val flow3 = flow {
  flow1.collect { emit(it) }
  flow2.collect { emit(it) }
}
is a solution but I'm wondering if there is a simpler solution 😉
l
flatMapConcat
s
I'm not sure this is the operator I'm looking for, since the returned
Flow
in the transform function will be applied to any value of
flow1
. So if I call
flow1.flatMapConcat { flow2 }
the result will be
4, 5, 6, 4, 5, 6, 4, 5, 6
So to be clear, every value of
flow1
and
flow2
should only be there once in the resulting flow 😉
m
You could do
flowOf(flow1, flow2).flattenConcat()
👍🏼 1
s
Thanks @marstran, this is what I was looking for
Hm, unfortunately still not really what I need because this is sequential. I mean this works in my example code but what if
flow1
for instance needs 5 seconds before producing the first value but
flow2
is faster? Then the first results will still be collected once
flow1
has produced it's values. Also what if any of the flows are not terminal?
m
If you want to merge them instead, you can use
flattenMerge()
.
👍🏼 1