sync<T> static method

void sync<T>({
  1. required String callId,
  2. required dynamic operation(),
  3. OnThrottle? onThrottle,
  4. OnError? onError,
  5. OnNull? onNull,
  6. OnEmpty? onEmpty,
  7. required void onSuccess(
    1. T data
    ),
  8. Duration throttle = const Duration(seconds: 1),
})

Throttles a synchronous operation by preventing it from being executed more frequently than the specified throttle duration, and executes a success callback with the result of the operation.

If the operation is already throttled, the onThrottle callback is executed and the operation is not performed.

If the operation returns null, the onNull callback is executed.

If the operation returns an empty iterable or map, the onEmpty callback is executed.

If the operation throws an error, the onError callback is executed.

The onSuccess callback is executed with the result of the operation if it completes successfully.

The callId parameter is used to uniquely identify each operation. The throttle parameter determines the duration of the throttling, and defaults to 1 second.

If you need to perform asynchronous operations, use the throttleFuture method instead.

Usage:

throttle<int>(
  callId: 'example',
  operation: () => 1 + 1,
  onThrottle: () => print('Operation is throttled'),
  onNull: () => print('Operation returned null'),
  onEmpty: () => print('Operation returned an empty iterable or map'),
  onSuccess: (result) => print('Operation result: $result'),
  throttle: const Duration(milliseconds: 500),
);

Implementation

static void sync<T>({
  required String callId,
  required Function() operation,
  OnThrottle onThrottle,
  OnError? onError,
  OnNull? onNull,
  OnEmpty? onEmpty,
  required void Function(T data) onSuccess,
  Duration throttle = const Duration(seconds: 1),
}) {
  if (_throttleTimers.containsKey(callId) &&
      _throttleTimers[callId]?.isActive == true) {
    onThrottle?.call();
    return;
  }

  _throttleTimers[callId] = Timer(throttle, () {});

  TryCatch.sync<T>(
    operation: () => operation(),
    onNull: onNull,
    onEmpty: onEmpty,
    onSuccess: onSuccess,
    onError: (e, s) => onError?.call(e, s),
  );
}