简体   繁体   中英

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

I want to create a Kotlin coroutines Flow that emits values when

  1. they change, and
  2. periodically emits the last value available, every x duration since the last change or last emit.

This seems to work -- every time a new value arrives, transformLatest cancels any previous lambdas and starts a new one. So this approach emits, and then continues to emit periodically until a new value arrives.

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

You could create a Flow that emits at a regular interval and then just use combine . Each time you'd combine the values, you'd really just be passing along the current value of the original Flow you are interested in.

    // 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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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