debounce method

Future<T?> debounce(
  1. T func()
)

Allows you to control events being triggered successively and, if the interval between two sequential occurrences is less than a certain amount of time (e.g. one second), it completely ignores the first one.

Implementation

Future<T?> debounce(T Function() func) async {
  if (_stateSC.isClosed) return null;
  if (isIdle) _stateSC.sink.add(DebouncingStatus.busy);
  final completer = _completer ??= Completer<T?>();
  _timer?.cancel();
  _timer = Timer(_duration, () {
    _completer = null;
    _timer = null;
    try {
      final result = func();
      completer.complete(result);
    } on Object catch (error, stackTrace) {
      completer.completeError(error, stackTrace); // coverage:ignore-line
    } finally {
      if (!_stateSC.isClosed) _stateSC.sink.add(DebouncingStatus.idle);
    }
  });
  return completer.future;
}