如何连接两个kotlin流?

发布于 2025-01-30 13:18:53 字数 216 浏览 3 评论 0原文

如前所述,我想依次连接两个流,因此合并无法正常工作。

例子:

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

As stated, I'd like to concatenate two flows sequentially therefore merge won't work.

Example:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

木格 2025-02-06 13:18:53

您可以为此使用FlattenConCat

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

Flow Builder:

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

You can use flattenConcat for this:

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

Or the flow builder:

fun <T> concatenate(vararg flows: Flow<T>) = flow {
    for (flow in flows) {
        emitAll(flow)
    }
}
浪漫人生路 2025-02-06 13:18:53

这应该有效:

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

This should work: 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文