retry<T> static method

Future<T> retry<T>(
  1. Future<T> action(), {
  2. int maxAttempts = 3,
  3. Duration delay = const Duration(seconds: 1),
  4. bool onError(
    1. Object
    )?,
})

Retries a function with exponential backoff

Example:

final result = await Helpers.retry(
  () => apiCall(),
  maxAttempts: 3,
  delay: Duration(seconds: 1),
);

Implementation

static Future<T> retry<T>(
  Future<T> Function() action, {
  int maxAttempts = 3,
  Duration delay = const Duration(seconds: 1),
  bool Function(Object)? onError,
}) async {
  int attempts = 0;
  while (attempts < maxAttempts) {
    try {
      return await action();
    } catch (e) {
      attempts++;
      if (attempts >= maxAttempts) rethrow;
      if (onError != null && !onError(e)) rethrow;
      await Future.delayed(delay * attempts); // Exponential backoff
    }
  }
  throw Exception('Max retry attempts reached');
}