Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine results of more than 2 api calls with Coroutines Flow?

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.

like image 932
Thracian Avatar asked Sep 18 '20 10:09

Thracian


1 Answers


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

like image 81
IR42 Avatar answered Oct 07 '22 07:10

IR42