[英]Combine two kotlin flows into a single flow that emits the latest value from the two original flows?
[英]Flow that emits the last value periodically, and when a new value arrives
我想创建一个 Kotlin 协程Flow
,它在
这似乎有效——每次新值到达时, 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.