throttle method

void throttle(
  1. String id,
  2. Duration duration,
  3. FutureOr<void> action()
)
inherited

Throttles action, executing it immediately and rate-limiting subsequent calls to at most once per duration.

Subsequent calls with the same id within the duration are ignored. Automatically cancels active timers when the store is disposed.

Implementation

void throttle(
  String id,
  Duration duration,
  FutureOr<void> Function() action,
) {
  if (_disposed) return;
  if (_throttleTimers.containsKey(id)) return;

  // leading-edge: execute immediately
  try {
    final FutureOr<void> result = action();
    if (result is Future<void>) {
      result.catchError((Object exception, StackTrace stackTrace) {
        FlutterError.reportError(FlutterErrorDetails(
          exception: exception,
          stack: stackTrace,
          library: 'orbit',
          context: ErrorDescription(
              'inside throttled async action "$id" in $runtimeType'),
        ));
      });
    }
  } catch (exception, stackTrace) {
    FlutterError.reportError(FlutterErrorDetails(
      exception: exception,
      stack: stackTrace,
      library: 'orbit',
      context:
          ErrorDescription('inside throttled action "$id" in $runtimeType'),
    ));
  }

  _throttleTimers[id] = Timer(duration, () {
    _throttleTimers.remove(id);
  });
}