throttle<T> method

void throttle<T>(
  1. DebounceCallback<T> callback, {
  2. Duration duration = const Duration(milliseconds: 300),
  3. DebounceResultConsumer<T>? consumer,
  4. DebounceErrorConsumer? errorConsumer,
})

Throttle a callback.

  • callback: The callback to be throttled.
  • duration: The duration to wait before calling the callback.
  • consumer: The consumer to be called when the callback is called.
  • errorConsumer: The consumer to be called when the callback throws an error.

Implementation

void throttle<T>(
  DebounceCallback<T> callback, {
  Duration duration = const Duration(milliseconds: 300),
  DebounceResultConsumer<T>? consumer,
  DebounceErrorConsumer? errorConsumer,
}) {
  assert(!_debugDisposed, 'DebounceController is disposed');
  if (_session == null) {
    _session = _DebounceTimerSession(Timer(
      duration,
      () {
        _session = null;
        notifyListeners();
      },
    ));
    notifyListeners();
    try {
      var result = callback();
      if (result is Future<T>) {
        result.then((value) {
          consumer?.call(value);
        }).catchError((error, stackTrace) {
          errorConsumer?.call(error, stackTrace);
        });
        return;
      } else {
        consumer?.call(result);
      }
    } catch (error, stackTrace) {
      errorConsumer?.call(error, stackTrace);
    }
  }
}