With zip
or combine
it's only possible to combine only 2 flows if i don't miss anything, i wasn't able to see any public method that combines list of flows or vararg
.
for instance
apiHelper.getUsers()
.zip(apiHelper.getMoreUsers()) { usersFromApi, moreUsersFromApi ->
val allUsersFromApi = mutableListOf<ApiUser>()
allUsersFromApi.addAll(usersFromApi)
allUsersFromApi.addAll(moreUsersFromApi)
return@zip allUsersFromApi
}
i need first 5 pages from REST api, and fetch them in parallel and combine the result, do some mapping, and filtering on combined data. Can i combine them with flow
or should i pass coroutineScope and use async for having parallel requests?
I checked out the answer here but it returns compile error, and there seems to be no public combine function for flow that takes list as parameter.
val f1 = flow {
emit(listOf(1, 2))
}
val f2 = flow {
emit(listOf(3, 4))
}
val f3 = flow {
emit(listOf(5, 6))
}
suspend fun main() {
combine(f1, f2, f3) { elements: Array<List<Int>> ->
elements.flatMap { it }
}.collect {
println(it) // [1, 2, 3, 4, 5, 6]
}
combine(f1, f2, f3) { list, list2, list3 ->
list + list2 + list3
}.collect {
println(it) // [1, 2, 3, 4, 5, 6]
}
}
val fA: Flow<A> = ...
val fB: Flow<B> = ...
suspend fun main() {
val fCombined = combine(fA, fB) { a: A, b: B ->
...
}
}
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/combine.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With