retry<T> static method

Future<T> retry<T>(
  1. Future<T> action(), {
  2. int retries = 3,
  3. Duration delay = Duration.zero,
  4. bool retryIf(
    1. Object error
    )?,
})

Retries an async action until it succeeds or retries is exhausted.

Implementation

static Future<T> retry<T>(
  Future<T> Function() action, {
  int retries = 3,
  Duration delay = Duration.zero,
  bool Function(Object error)? retryIf,
}) async {
  if (retries < 0) {
    throw RangeError.value(retries, 'retries', 'must not be negative');
  }

  var attempt = 0;
  while (true) {
    try {
      return await action();
    } catch (error) {
      final shouldRetry = attempt < retries && (retryIf?.call(error) ?? true);
      if (!shouldRetry) rethrow;
      attempt++;
      if (delay > Duration.zero) {
        await Future<void>.delayed(delay);
      }
    }
  }
}