14

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.

Thracian
  • 43,021
  • 16
  • 133
  • 222

1 Answers1

25

There are top level combine functions


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> = ...
val fС: Flow<С> = ...

suspend fun main() {
    val fCombined = combine(fA, fB, fС) { a: A, b: B, c: C ->
        ...
    }
}
IR42
  • 8,587
  • 2
  • 23
  • 34