Search code examples
kotlinkotlin-flow

How can I limit a flow to a certain frequency window?


I have a wrapped an external optimization library in a callbackFlow in my quarkus-kotlin backend. Now I want to push updates to my frontend, but since updates from this library arrive quite frequently (at least during the first processing steps), it makes sense to limit the update frequency to save bandwidth.

I would like to send an update whenever a better solution to the optimization problem becomes available, but not more than once every sec (let's take 5 for this example) seconds.

I know about debounce, but the documentation on that clearly states, that the resulting flow only emits a value if there hasn't been an update for the duration of a specified timeout, so it's not really the behavior I want to achieve.

My current approach is to use conflate followed by onEach with a delay like this:

callbackFlow {
    // ...
}
    .conflate()
    .onEach {
        delay(5000)
    }

Is there a better or more idiomatic way to achieve this?


Solution

  • Instead of conflate and onEach you could use this:

    .sample(5.seconds)
    

    From the documentation:

    Returns a flow that emits only the latest value emitted by the original flow during the given sampling period.


    I'm not sure if this applies, by when you emit the same value a lot, then using distinctUntilChanged might also be an option.