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

Kotlin相关问答推荐

Fleet无法从构建文件自动重新加载更改错误'

只能在元素区域中点击的Jetpack Compose列

可以从背景图像中点击图标吗?

数据流弹性模板失败,出现错误&未知非复合转换urn";

如何使用multiset与JOOQ获取关联的记录列表?

在Kotlin lambda的参数中如何指定函数类型?

修改器的属性是什么,我需要更改以使角变圆且宽度更小?喷气背包组合

KMM:编译失败:意外的 IrType 类型:KIND_NOT_SET

如何为你的 Flutter 元素添加 Kotlin 支持?

Kotlin:内部类如何访问在外部类中声明为参数的变量?

如何在Kotlin中创建填充空值的通用数组?

使用Dagger 2提供函数依赖性

如何在 Jetpack Compose 的 LazyColumn/LazyRow 中禁用和启用滚动?

如何在Kotlin中使用ViewModelProviders

项目未与 Gradle 链接

Android Kotlin 创建类实现 Parcelable 在 writeToParcel 方法的 override中给出错误

什么是 Kotlin 等价于 Class<?>

Kotlin类型安全类型别名

Kotlin - 如果不为空,则使用修改后的 Obj props 覆盖 Obj props

在 IntelliJ Idea 中未为 Kotlin @ConfigurationProperties 类生成 spring-configuration-metadata.json 文件