attempt<T> method

Future<T?> attempt<T>(
  1. Future<T> operation(), {
  2. bool isCancelled()?,
})

Attempt operation with retries and backoff. isCancelled optional callback to check for cancellation.

Implementation

Future<T?> attempt<T>(
  Future<T> Function() operation, {
  bool Function()? isCancelled,
}) async {
  int attempt = 0;

  while (true) {
    if (isCancelled?.call() ?? false) return null;

    try {
      return await operation();
    } catch (_) {
      attempt++;
      if (attempt > maxRetries) return null;
      final delay = backoff.nextDelay(attempt);
      if (delay > Duration.zero) {
        await Future.delayed(delay);
      }
    }
  }
}