相关疑难解决方法(0)

将多个 Kotlin 流合并到一个列表中,无需等待第一个值

我有一个List<Flow<T>>,想生成一个Flow<List<T>>. 这几乎是什么combine- 除了组合等待每个都Flow发出初始值,这不是我想要的。以这段代码为例:

val a = flow {
  repeat(3) {
    emit("a$it")
    delay(100)
  }
}
val b = flow {
  repeat(3) {
    delay(150)
    emit("b$it")
  }
}
val c = flow {
  delay(400)
  emit("c")
}
val flows = listOf(a, b, c)
runBlocking {
  combine(flows) {
    it.toList()
  }.collect { println(it) }
}
Run Code Online (Sandbox Code Playgroud)

使用combine(因此按原样),这是输出:

[a2, b1, c]
[a2, b2, c]
Run Code Online (Sandbox Code Playgroud)

而我也对所有中间步骤感兴趣。这就是我想要从这三个流程中得到的:

[]
[a0]
[a1]
[a1, b0]
[a2, b0]
[a2, b1]
[a2, b1, c]
[a2, …
Run Code Online (Sandbox Code Playgroud)

kotlin kotlin-coroutines kotlin-flow

9
推荐指数
1
解决办法
6900
查看次数

标签 统计

kotlin ×1

kotlin-coroutines ×1

kotlin-flow ×1