Kotlin 当新值到达时,周期性地发出最后一个值的流
我想创建一个Kotlin协程Kotlin 当新值到达时,周期性地发出最后一个值的流,kotlin,kotlin-coroutines,Kotlin,Kotlin Coroutines,我想创建一个Kotlin协程流,当 他们改变了,而且 自上次更改或上次发射后,每隔x个持续时间定期发射最后一个可用值 这似乎有效——每次新值到达时,transformLatest都会取消以前的lambda并启动一个新的lambda。因此,这种方法会发射,然后继续定期发射,直到新值到达为止 flow.transformLatest{value-> while(currentCoroutineContext().isActive){ 发射(值) 延迟(x) } } 您可以创建一个定期发射的流,然后使
流
,当
transformLatest
都会取消以前的lambda并启动一个新的lambda。因此,这种方法会发射,然后继续定期发射,直到新值到达为止
flow.transformLatest{value->
while(currentCoroutineContext().isActive){
发射(值)
延迟(x)
}
}
您可以创建一个定期发射的流,然后使用组合。每次组合这些值时,实际上只是传递您感兴趣的原始流的当前值
// 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
}
您可以删除isActive
复选框。取消操作的工作原理相同。为True,但while
循环时不会出现任何条件错误。我喜欢明确的检查所提供的额外思维。