executeWithRetry<T> function

Future<T> executeWithRetry<T>(
  1. Future<T> function(),
  2. RetryPolicy retryPolicy
)

Helper function to execute a function with a retry policy.

This can be used directly when retry behavior is needed outside of FLimit.

Implementation

Future<T> executeWithRetry<T>(
  Future<T> Function() function,
  RetryPolicy retryPolicy,
) async {
  int attempt = 0;

  while (true) {
    try {
      return await function();
    } catch (error, stackTrace) {
      if (!retryPolicy.shouldRetry(attempt, error, stackTrace)) {
        rethrow;
      }

      final delay = retryPolicy.nextDelay(attempt, error, stackTrace);
      if (delay != null) {
        await Future.delayed(delay);
      }

      attempt++;
    }
  }
}