run<T> static method

Future<T> run<T>({
  1. required Future<T> operation(),
  2. int maxAttempts = 3,
  3. Duration initialDelay = const Duration(milliseconds: 500),
  4. Duration maxDelay = const Duration(seconds: 8),
  5. bool shouldRetry(
    1. Object error
    )?,
  6. void onRetry(
    1. int attempt,
    2. Object error
    )?,
})

Implementation

static Future<T> run<T>({
  required Future<T> Function() operation,
  int maxAttempts = 3,
  Duration initialDelay = const Duration(milliseconds: 500),
  Duration maxDelay = const Duration(seconds: 8),
  bool Function(Object error)? shouldRetry,
  void Function(int attempt, Object error)? onRetry,
}) async {
  assert(maxAttempts >= 1);

  Object? lastError;
  StackTrace? lastStack;
  var delay = initialDelay;

  for (int attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await operation();
    } catch (e, st) {
      lastError = e;
      lastStack = st;

      if (attempt >= maxAttempts) break;
      if (shouldRetry != null && !shouldRetry(e)) break;

      onRetry?.call(attempt, e);

      await Future.delayed(_jittered(delay));
      delay = _nextDelay(delay, maxDelay);
    }
  }

  Error.throwWithStackTrace(lastError!, lastStack ?? StackTrace.current);
}