You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kotlin Flow函数内部返回另一个Flow,避免链式调用?

实现Kotlin Flow内部发送初始值后串联子Flow并收集全部结果

首先是你已有的getNumbers2函数:

fun getNumbers2(input: Int): Flow<Int> = callbackFlow {
    for (i in 1..5) {
        send(i + input)
        delay(1000)
    }
    close()
}

要实现getNumbers1内部先发送input值,再串联getNumbers2(input)的所有输出,直接用flow构建器结合emit和emitAll即可,无需外部链式调用flatMapMerge:

fun getNumbers1(input: Int): Flow<Int> = flow {
    // 先发送初始的input值
    emit(input)
    // 再发送getNumbers2的所有输出
    emitAll(getNumbers2(input))
}

调用示例

直接收集getNumbers1就能同时拿到初始input和getNumbers2的所有结果:

// 注意:实际开发中尽量避免使用GlobalScope,建议使用生命周期绑定的CoroutineScope
GlobalScope.launch(Dispatchers.IO) {
    getNumbers1(10).collect {
        println("Result: $it")
    }
}

输出结果

执行后会依次打印:

Result: 10
Result: 11
Result: 12
Result: 13
Result: 14
Result: 15

原理说明

  • 使用emit可以向Flow发送单个元素,这里先把初始的input值发送出去;
  • 使用emitAll可以将另一个Flow的所有元素全部发送到当前Flow中,相当于把getNumbers2的输出直接串联在初始值之后;
  • 这样外部调用时无需额外的flatMap操作,直接collect就能获取所有结果。

内容的提问来源于stack exchange,提问作者Anggrayudi H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 08:12:46