https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

svenjacobs

08/30/2019, 6:15 AM
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

louiscad

08/30/2019, 6:26 AM
flatMapConcat
s

svenjacobs

08/30/2019, 6:34 AM
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

marstran

08/30/2019, 7:07 AM
You could do
flowOf(flow1, flow2).flattenConcat()
👍🏼 1
s

svenjacobs

08/30/2019, 7:09 AM
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

marstran

08/30/2019, 7:35 AM
If you want to merge them instead, you can use
flattenMerge()
.
👍🏼 1
2 Views