【问题标题】:How to combine results from a suspend function and a flow in kotlin?如何在 kotlin 中结合挂起函数和流的结果?
【发布时间】:2021-12-28 15:18:48
【问题描述】:

大家想象我有这两个数据来源:

val flowA: Flow<String>
suspend fun funB(): Int

如何将两者的结果组合成一个流程(比如Flow&lt;Pair&lt;String, Int&gt;&gt;)?

下面的方法怎么样?有没有更好的办法?

combine(
  flowA,
  flow {emit(funB())}
) { a, b ->
  ...
}

【问题讨论】:

  • 你想把同一个 Int 和所有字符串放在一起吗?

标签: kotlin reactive-programming flow suspend


【解决方案1】:

假设您希望与flowA 中的每个字符串配对相同的Int,您可以按如下方式进行:

val funBResult = funB()
val pairs = flowA.map { it to funBResult }

如果funB() 实际上是一个将String 作为参数的函数,您可以执行以下操作:

val pairs = flowA.map { it to funB(it) }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-21
    • 2021-06-25
    • 2021-01-02
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    相关资源
    最近更新 更多