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

Lukas Lechner

08/25/2022, 1:30 PM
The Coroutines docs discourage the use of
flatMapMerge
and
flatMapConcat
in regular application-specific flows, see attached image. What should we used instead when flatMapping two flows?
t

Trevor Stone

08/25/2022, 2:13 PM
flatMapLatest
so prior work is canceled if that's what you want it. Otherwise what they're saying is that you could use a
transform
or
map
and collect from the child flow and emit downstream. If you feel that you and your team are comfortable using
merge
and
concat
though I personally wouldn't see it as an issue. I think the docs are written from someone that knows
coroutines
and is learning
flow
vs someone who knows something like
rxJava
and learning
flow
l

Lukas Lechner

08/25/2022, 2:49 PM
Thanks! Interesting, that
flatMapLatest
is basically only using
transformLatest
under the hood...
I now know how I can replace
flatMapX
with
transform
, but how can I replace it with
map
? I can only map a single value and cannot emit multiple emissions from a map, right?
t

Trevor Stone

08/25/2022, 10:13 PM
so map is just
Copy code
public inline fun <T, R> Flow<T>.map(crossinline transform: suspend (value: T) -> R): Flow<R> = transform { value ->
    return@transform emit(transform(value))
}
so you're right. It would be for 1 item in 1 item out transforms
possibly when they mention it looks familiar it might be referencing
flatmap
on collections https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/flat-map.html which I could see being confusing for people
r

Raheel Naz [Amex]

08/26/2022, 8:38 PM
the one key difference between the two is if you use
flattenConcat
a suspended collect will actually block other flows from emitting data downstream because order matters
31 Views