debounce<T> function

Worker debounce<T>(
  1. GetListenable<T> listener,
  2. WorkerCallback<T> callback, {
  3. Duration? time,
  4. Function? onError,
  5. void onDone()?,
  6. bool? cancelOnError,
})

debounce is similar to interval, but sends the last value. Useful for Anti DDos, every time the user stops typing for 1 second, for instance. When listener emits the last "value", when time hits, it calls callback with the last "value" emitted.

Sample:

worker = debounce(
     count,
     (value) {
       print(value);
       if( value > 20 ) worker.dispose();
     },
     time: 1.seconds,
   );
 }

Implementation

Worker debounce<T>(
  GetListenable<T> listener,
  WorkerCallback<T> callback, {
  Duration? time,
  Function? onError,
  void Function()? onDone,
  bool? cancelOnError,
}) {
  final newDebouncer =
      Debouncer(delay: time ?? const Duration(milliseconds: 800));
  StreamSubscription sub = listener.listen(
    (event) {
      newDebouncer(() {
        callback(event);
      });
    },
    onError: onError,
    onDone: onDone,
    cancelOnError: cancelOnError,
  );
  return Worker(sub.cancel, '[debounce]');
}