繁体   English   中英

定期发出最后一个值的流,当一个新值到达时

[英]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.
    val emitter = flow {
        emit("Your data")
        // ...
    }
    // This just serves as a timer.
    val timer = flow {
        // Set this up to emit at a regular interval for as
        // many times as you'd like.
        repeat(100) {
            emit(Unit)
            delay(500)
        }
    }
    // This will emit whenever either of the Flows emits
    combine(
        emitter,
        timer
    ) {  value, ticker ->
        // Always just return the value of your
        // main Flow.
        value
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM