retry<T> static method
Retries an async action until it succeeds or retries is exhausted.
Implementation
static Future<T> retry<T>(
Future<T> Function() action, {
int retries = 3,
Duration delay = Duration.zero,
bool Function(Object error)? retryIf,
}) async {
if (retries < 0) {
throw RangeError.value(retries, 'retries', 'must not be negative');
}
var attempt = 0;
while (true) {
try {
return await action();
} catch (error) {
final shouldRetry = attempt < retries && (retryIf?.call(error) ?? true);
if (!shouldRetry) rethrow;
attempt++;
if (delay > Duration.zero) {
await Future<void>.delayed(delay);
}
}
}
}