retryTimes<T> function

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

Retries fn up to times attempts; rethrows on final failure.

Implementation

Future<T> retryTimes<T>(
  AsyncAction<T> fn,
  int times,
) async {
  int attempts = 0;

  while (true) {
    try {
      return await fn();
    } on Object catch (e, st) {
      attempts++;
      if (attempts >= times) {
        debugPrint(
          'retryTimes failed after $times: $e\n$st',
        );
        rethrow;
      }
    }
  }
}