throttle method

Stream<T> throttle(
  1. Duration duration, {
  2. bool trailing = false,
})

Reduces the rate that events are emitted to at most once per duration.

No events will ever be emitted within duration of another event on the result stream. If this stream is a broadcast stream, the result will be as well. Errors are forwarded immediately.

If trailing is false, source events emitted during the duration period following a result event are discarded. The result stream will not emit an event until this stream emits an event following the throttled period. If this stream is consistently emitting events with less than duration between events, the time between events on the result stream may still be more than duration. The result stream will close immediately when this stream closes.

If trailing is true, the latest source event emitted during the duration period following an result event is held and emitted following the period. If this stream is consistently emitting events with less than duration between events, the time between events on the result stream will be duration. If this stream closes the result stream will wait to emit a pending event before closing.

For example:

source.throtte(Duration(seconds: 6));

source: 1-2-3---4-5-6---7-8-|
result: 1-------4-------7---|

source.throttle(Duration(seconds: 6), trailing: true);

source: 1-2-3---4-5----6--|
result: 1-----3-----5-----6|

source.throttle(Duration(seconds: 6), trailing: true);

source: 1-2-----------3|
result: 1-----2-------3|

See also:

  • audit, which emits the most recent event at the end of the period. Compared to audit, throttle will not introduce delay to forwarded elements, except for the trailing events.
  • debounce, which uses inter-event spacing instead of a fixed period from the first event in a window. Compared to debouce, throttle cannot be starved by having events emitted continuously within duration.

Implementation

Stream<T> throttle(Duration duration, {bool trailing = false}) =>
    trailing ? _throttleTrailing(duration) : _throttle(duration);