kotlinkotlin-coroutineskotlin-flowticker

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.

Solution

  • 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)
      }
    }