如何连接两个科特林流程?

How to concatenate two kotlin flows?

如前所述,我想按顺序连接两个流,因此 merge 不起作用。

示例:

val f1 = flowOf(1, 2)
val f2 = flowOf(3, 4)
val f = concatenate(f1, f2) // emits 1, 2, 3, 4

这应该有效:onCompletion

val f1 = flowOf(1,2,3)
val f2 = flowOf(4,5,6)
val f = f1.onCompletion{emitAll(f2)}
runBlocking {
   f.collect {
        println(it)
   }
}

//Result: 1 2 3 4 5 6

您可以为此使用 flattenConcat

fun <T> concatenate(vararg flows: Flow<T>) =
    flowOf(*flows).flattenConcat()

flow 建造者:

fun <T> concatenate(vararg flows: Flow<T>) = flow {
    for (flow in flows) {
        emitAll(flow)
    }
}