throttle<T> static method

LxWorker<T> throttle<T>(
  1. LxReactive<T> source,
  2. Duration duration,
  3. void callback(
    1. T value
    ), {
  4. dynamic onProcessingError(
    1. Object error,
    2. StackTrace stackTrace
    )?,
})

Triggers callback immediately, then ignores updates for duration.

Implementation

static LxWorker<T> throttle<T>(
  LxReactive<T> source,
  Duration duration,
  void Function(T value) callback, {
  Function(Object error, StackTrace stackTrace)? onProcessingError,
}) {
  Timer? timer;
  var isThrottled = false;
  return _LxManagedWorker<T>(
    source,
    (value) {
      if (isThrottled) return;
      isThrottled = true;
      try {
        callback(value);
      } catch (e, st) {
        if (onProcessingError != null) {
          onProcessingError(e, st);
        } else {
          Zone.current.handleUncaughtError(e, st);
        }
      }
      timer?.cancel();
      timer = Timer(duration, () {
        isThrottled = false;
      });
    },
    onProcessingError: onProcessingError,
    onClose: () {
      timer?.cancel();
      timer = null;
      isThrottled = false;
    },
  );
}