How to throttle a Flux

Viewed 674

Using Reactor, I would like to limit the rate at which events are published from a Flux, e.g. to a maximum of 10 Hz, while discarding all elements in between. The only thing I found is delayElements(), but this will queue up elements if they arrive at a faster rate, right? I'd like to some somethings like someFlux.throttle(10).subscribe() to make the Flux return at max. 10 elements a second.

1 Answers

there is a sample(Duration), so you could do:

source.sample(Duration.ofMillis(100));

(100 milliseconds = 1/10th of a second, so you'd get at most 1 element every 100ms, ie. 10 elements every second)

edit: for a proper throttle, consider also sampleFirst(v -> Mono.delay(Duration.ofMillis(100)) to drop all items that follow a propagated item within 100ms

Related