debounce method

Stream<T> debounce(
  1. Duration duration
)

Suppresses events that arrive within duration of each other, emitting only the last one in each quiet window (debounce).

Implementation

Stream<T> debounce(Duration duration) {
  StreamController<T>? controller;
  Timer? timer;

  controller = StreamController<T>(
    onListen: () {
      listen(
        (value) {
          timer?.cancel();
          timer = Timer(duration, () => controller!.add(value));
        },
        onError: controller!.addError,
        onDone: () {
          timer?.cancel();
          controller!.close();
        },
      );
    },
  );
  return controller.stream;
}