如何在 Kotlin Flow 中添加动态值

How add dynamic values in Kotlin Flow

如果我们知道要在 Kotlin 流程中处理的列表值,那么我们可以遵循以下函数

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

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

就我而言,我在流程开始时没有输入值。我想在我有值 1 时开始流程,同时如果我有一个新值,我必须将它添加到队列中,等待值 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 完成它的工作。