execute<T> method

Future<T?> execute<T>({
  1. required Future<T> action(),
  2. void onRetry(
    1. int attempt,
    2. Object error
    )?,
  3. Duration delayOverride(
    1. int attempt
    )?,
})

Executes action with retry and exponential backoff.

Returns the result of action on success. Returns null if all retries are exhausted. Calls onRetry before each retry attempt.

Implementation

Future<T?> execute<T>({
  required Future<T> Function() action,
  void Function(int attempt, Object error)? onRetry,
  Duration Function(int attempt)? delayOverride,
}) async {
  for (var attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await action();
    } catch (e) {
      if (attempt >= maxRetries) {
        return null;
      }
      onRetry?.call(attempt, e);
      final delay = delayOverride?.call(attempt) ??
          Duration(milliseconds: delayForAttempt(attempt));
      await Future<void>.delayed(delay);
    }
  }
  return null;
}