定期发出最后一个值并在新值到达时发出的流

Flow that emits the last value periodically, and when a new value arrives

我想创建一个 Kotlin 协程 Flow,它在

时发出值
  1. 他们改变了,并且
  2. 定期发出最后一个可用值,自上次更改或上次发出后每隔 x 持续时间。

这似乎行得通 -- 每次新值到达时,transformLatest 都会取消所有先前的 lambda 并启动一个新的。所以这种方法发出,然后继续周期性地发出,直到一个新的值到达。

flow.transformLatest { value ->
  while(currentCoroutineContext().isActive) {
    emit(value)
    delay(x)
  }
}

您可以创建一个定期发出的 Flow,然后只需使用 combine。每次合并这些值时,您实际上只是传递了您感兴趣的原始 Flow 的当前值。

    // This is the main flow you are interested in. This uses
    // a Flow builder just as a simple example but this could
    // be any kind of Flow, like a (Mutable)StateFlow.
    val emitter = flow {
        emit("Your data")
        // ...
    }
    // This just serves as a timer.
    val timer = flow {
        while (currentCoroutineContext().isActive) {
            emit(Unit)
            delay(500)
        }
    }
    // This will emit whenever either of the Flows emits and 
    // continues to do so until "emitter" stops emitting.
    combine(
        emitter,
        timer
    ) {  value, ticker ->
        // Always just return the value of your
        // main Flow.
        value
    }