kotlin - 如何连接两个 kotlin 流?

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

例子:

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

回答1

您可以为此使用 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)
    }
}

回答2

这应该有效:https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/on-completion.html

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

相似文章

随机推荐

最新文章