async<T> static method

Future<void> async<T>({
  1. required String callId,
  2. required Future<T> operation,
  3. OnTimeout? onTimeout,
  4. OnError? onError,
  5. OnWaiting? onWaiting,
  6. OnNull? onNull,
  7. OnEmpty? onEmpty,
  8. OnThrottle? onThrottle,
  9. required void onSuccess(
    1. T data
    ),
  10. Duration duration = const Duration(seconds: 1),
  11. Duration timeout = const Duration(milliseconds: 0),
})

Throttles the execution of an asynchronous operation and handles its result or errors based on the given callback functions. The callId parameter is used to identify the operation and avoid concurrent executions. The operation parameter is the asynchronous operation to be throttled, and duration is the duration of the throttling period.

The optional onTimeout, onError, onWaiting, onNull, onEmpty, and onThrottle parameters are callbacks that are called depending on the result or error of the operation or if the operation is waiting or is throttled. The required onSuccess parameter is a callback that is called with the result of the operation if it is successful.

The optional timeout parameter is the maximum duration that the operation is allowed to execute before it times out.

Usage:

await Throttle.async<int>(
  callId: 'example',
  operation: () async {
    // perform some async operation
    await Future.value(100);
  },
  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'),
  duration: const Duration(milliseconds: 500),
  timeout: const Duration(seconds: 5),
);

Implementation

static Future<void> async<T>({
  required String callId,
  required Future<T> operation,
  OnTimeout onTimeout,
  OnError onError,
  OnWaiting onWaiting,
  OnNull onNull,
  OnEmpty onEmpty,
  OnThrottle onThrottle,
  required void Function(T data) onSuccess,
  Duration duration = const Duration(seconds: 1),
  Duration timeout = const Duration(milliseconds: 0),
}) async {
  if (_throttleTimers.containsKey(callId) &&
      _throttleTimers[callId]?.isActive == true) {
    onThrottle?.call();
    return;
  }

  _throttleTimers[callId] = Timer(duration, () async {
    _throttleTimers.remove(callId);
  });

  await TryCatch.async<T>(
    future: operation,
    onNull: onNull,
    onEmpty: onEmpty,
    onSuccess: onSuccess,
    onTimeout: onTimeout,
    onWaiting: onWaiting,
    onError: (e, s) => onError?.call(e, s),
    timeout: timeout,
  );
}