【问题标题】:How add dynamic values in Kotlin Flow如何在 Kotlin Flow 中添加动态值
【发布时间】:2021-07-06 09:14:41
【问题描述】:

如果我们知道要在 Kotlin 流程中处理的列表值,那么我们可以按照以下函数进行操作

  flow {
          (1..1000).forEach {
            delay(1000) //Process Data
            emit(it.toLong())
          }
       }.collect{
            delay(2000)
            print(it)
        }

我们知道我们将打印从 1 到 1000 的值

就我而言,我在流程开始时没有输入值。我想在我有值 1 时启动流程并开始数据处理,同时如果我有一个新值,那么我必须将它添加到队列中,等待值 1 被处理然后开始新值的处理。

基本上,我想在流程块之外添加价值,是否有任何解决方案可以实现这一目标?

【问题讨论】:

    标签: android kotlin kotlin-coroutines kotlin-flow android-ktx


    【解决方案1】:

    您可以将SharedFlow 用于缓冲区。应该是这样的:

    val myFlow = MutableSharedFlow<Long>()
    

    你可以发出这样的值:

    (1..1000).forEach {
        delay(1000) //Process Data
        println("Emitting $it")
        myFlow.emit(it.toLong())
    }
    

    然后像这样收集它们:

    myFlow
        .buffer()
        .collect {
            delay(2000)
            println("Received: $it")
        }
    

    如果您不使用 buffer 运算符,则每次发出值时,发出都会暂停,直到 collect 完成其工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 2021-10-31
      相关资源
      最近更新 更多