retryWithBackoff<T> function

Future<T> retryWithBackoff<T>(
  1. AsyncAction<T> fn, {
  2. int maxAttempts = 3,
  3. Duration initialDelay = _defaultInitialDelay,
  4. bool isExponential = true,
})

Retry with backoff (exponential or linear). Roadmap #178.

Implementation

Future<T> retryWithBackoff<T>(
  AsyncAction<T> fn, {
  int maxAttempts = 3,
  Duration initialDelay = _defaultInitialDelay,
  bool isExponential = true,
}) async {
  int attempt = 0;
  while (true) {
    try {
      return await fn();
    } on Object catch (e) {
      dev.log('retry attempt $attempt failed', error: e);
      attempt++;
      if (attempt >= maxAttempts) rethrow;
      final Duration delay = isExponential
          ? Duration(
              milliseconds: initialDelay.inMilliseconds * (1 << (attempt - 1)),
            )
          : Duration(
              milliseconds: initialDelay.inMilliseconds * attempt,
            );
      await Future<void>.delayed(delay);
    }
  }
}