debounce static method

TileUpdateTransformer debounce(
  1. Duration duration
)

Suppresses tile updates with less inter-event spacing than duration

This may improve performance, and reduce the number of tile requests, but at the expense of UX: new tiles will not be loaded until duration after the final tile load event in a series. For example, a fling gesture will not load new tiles during its animation, only at the end. Best used in combination with the cancellable tile provider, for even more fine-tuned optimization.

Implementation follows that in 'package:stream_transform'.

Also see throttle.


Ignores events where it is one of:

These events alone will not cause the camera to change position, and therefore tile updates are necessary.

Implementation

static TileUpdateTransformer debounce(Duration duration) {
  Timer? timer;
  TileUpdateEvent? soFar;
  var hasPending = false;
  var shouldClose = false;

  return StreamTransformer.fromHandlers(
    handleData: (event, sink) {
      if (event.wasTriggeredByTap()) return;

      void emit() {
        sink.add(soFar!);
        soFar = null;
        hasPending = false;
      }

      timer?.cancel();
      soFar = event;
      hasPending = true;

      timer = Timer(duration, () {
        emit();
        if (shouldClose) sink.close();
        timer = null;
      });
    },
    handleDone: (sink) {
      if (hasPending) {
        shouldClose = true;
      } else {
        timer?.cancel();
        sink.close();
      }
    },
  );
}