retryTimes<T> function

Future<T> retryTimes<T>(
  1. AsyncAction<T> fn,
  2. int times
)

Retries fn up to times attempts; rethrows on final failure. Audited: 2026-06-12 11:26 EDT

Implementation

Future<T> retryTimes<T>(
  AsyncAction<T> fn,
  int times,
) async {
  // At least one attempt: a non-positive `times` would otherwise rethrow on the
  // first failure (0 retries) yet still run fn once — clamp so the count is sane.
  final int maxAttempts = times < 1 ? 1 : times;
  int attempts = 0;

  while (true) {
    try {
      return await fn();
    } on Object catch (e, st) {
      attempts++;
      if (attempts >= maxAttempts) {
        // ignore: saropa_lints/avoid_print_error, saropa_lints/avoid_debug_print -- intentional diagnostic logging; debugPrint is stripped in release builds. The error is rethrown to the caller below.
        debugPrint(
          'retryTimes failed after $times: $e\n$st',
        );
        rethrow;
      }
    }
  }
}