gpt4 book ai didi

kotlin - 定期发出最后一个值以及新值到达时的流

转载 作者:行者123 更新时间:2023-12-02 18:46:49 25 4
gpt4 key购买 nike

我想创建一个 Kotlin 协程Flow,它在以下情况下发出值

  1. 他们会改变,并且
  2. 自上次更改或上次发出以来每 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
}

关于kotlin - 定期发出最后一个值以及新值到达时的流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67325125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com