retryWithPolicy<T> function

Future<T> retryWithPolicy<T>(
  1. Future<T> fn(), {
  2. int maxAttempts = 3,
  3. Duration delay = retryPolicyDefaultDelay,
  4. void onRetry(
    1. Object error,
    2. int attempt
    )?,
})

Retries fn up to maxAttempts with delay between attempts. Optional onRetry.

Implementation

Future<T> retryWithPolicy<T>(
  Future<T> Function() fn, {
  int maxAttempts = 3,
  Duration delay = retryPolicyDefaultDelay,
  void Function(Object error, int attempt)? onRetry,
}) async {
  int attempt = 0;
  while (true) {
    try {
      return await fn();
    } on Object catch (e, st) {
      log('retryWithPolicy attempt $attempt', error: e);
      attempt++;
      // ignore: saropa_lints/avoid_ignoring_return_values -- throwWithStackTrace returns Never; there is no value to capture
      if (attempt >= maxAttempts) Error.throwWithStackTrace(e, st);
      onRetry?.call(e, attempt);
      await Future<void>.delayed(delay);
    }
  }
}