retry<T> static method

Future<T> retry<T>(
  1. Future<T> task(), {
  2. int maxAttempts = 3,
  3. Duration delay = const Duration(milliseconds: 200),
  4. bool retryIf(
    1. Object error
    )?,
})

Retries task up to maxAttempts times with optional backoff.

await ChicoAsync.retry(
  () => api.fetch(),
  maxAttempts: 3,
  delay: Duration(milliseconds: 200),
);

Implementation

static Future<T> retry<T>(
  Future<T> Function() task, {
  int maxAttempts = 3,
  Duration delay = const Duration(milliseconds: 200),
  bool Function(Object error)? retryIf,
}) async {
  assert(maxAttempts > 0);
  Object? lastError;
  StackTrace? lastStack;
  for (var attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await task();
    } catch (error, stackTrace) {
      lastError = error;
      lastStack = stackTrace;
      final shouldRetry = retryIf?.call(error) ?? true;
      if (!shouldRetry || attempt == maxAttempts) {
        Error.throwWithStackTrace(error, stackTrace);
      }
      await Future<void>.delayed(delay * attempt);
    }
  }
  Error.throwWithStackTrace(
    lastError ?? StateError('retry failed'),
    lastStack ?? StackTrace.current,
  );
}