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

myanmarking

03/17/2020, 3:32 PM
what is the proper way of transforming a flow<List<T>> to a flow<T> ?
s

streetsofboston

03/17/2020, 3:36 PM
Flatmap?
Copy code
val listflow: Flow<List<Int>> = ...
val itemFlow: Flow<Int> = listFlow.flatMapConcat { it.asFlow() }
(not sure if Collection<T>.asFlow() or something similar exists, but it would not be hard to write yourself if it doesn’t)
m

myanmarking

03/17/2020, 3:37 PM
i mean an operator on flow
managed to make this one:
Copy code
fun <T> Flow<List<T>>.flatten(): Flow<T> {
    return flow {
        collect { values -> values.forEach { value -> emit(value) } }
    }
}
👍 2
i think it should work as intended
a

araqnid

03/17/2020, 3:59 PM
I’ve used
flatMapConcat { it.asFlow() }
or
flatMapMerge { it.asFlow() }
— flattening flows is potentially a bit more involved than a plain sequence
d

Dominaezzz

03/17/2020, 4:07 PM
Use
transform
for transforming flows.
Copy code
fun <T> Flow<List<T>>.flatten(): Flow<T> {
    return transform { values ->
        values.forEach { value -> emit(value) }
    }
}
m

myanmarking

03/17/2020, 4:09 PM
ok. thanks
a

araqnid

03/17/2020, 4:17 PM
transform
will always apply the transforms in series, not in parallel
5 Views