async<T> static method

void async<T>({
  1. required Object callId,
  2. required Future<T> operation,
  3. OnError? onError,
  4. OnWaiting? onWaiting,
  5. OnNull? onNull,
  6. OnEmpty? onEmpty,
  7. required void onSuccess(
    1. T data
    ),
  8. Duration duration = const Duration(milliseconds: 1000),
})

Runs an asynchronous operation with a debounce mechanism to limit multiple calls to the same operation. This method waits for a specified duration after a call with a specific callId has been made before running the operation.

When the operation is complete, the onSuccess callback is called with the result. You can also provide optional callbacks to handle errors, waiting states, null and empty data.

Example usage:

async<String>(
  callId: 'my_call_id',
  operation: fetchSomeData(),
  onSuccess: (data) => print('Got data: $data'),
);

Implementation

static void async<T>({
  required Object callId,
  required Future<T> operation,
  OnError onError,
  OnWaiting onWaiting,
  OnNull onNull,
  OnEmpty onEmpty,
  required void Function(T data) onSuccess,
  Duration duration = const Duration(milliseconds: 1000),
}) {
  if (_debounceTimers.containsKey(callId)) {
    _debounceTimers[callId]?.cancel();
  }

  _debounceTimers[callId] = Timer(duration, () async {
    await TryCatch.async<T>(
      future: operation,
      onError: onError,
      onWaiting: onWaiting,
      onNull: onNull,
      onEmpty: onEmpty,
      onSuccess: onSuccess,
    );
    _debounceTimers.remove(callId);
  });
}