run<T> static method
Future<T>
run<
T>({ - required Future<T> operation(),
- int maxAttempts = 3,
- Duration initialDelay = const Duration(milliseconds: 500),
- Duration maxDelay = const Duration(seconds: 8),
- bool shouldRetry(
- Object error
)?,
- void onRetry(
- int attempt,
- Object error
)?,
})
Implementation
static Future<T> run<T>({
required Future<T> Function() operation,
int maxAttempts = 3,
Duration initialDelay = const Duration(milliseconds: 500),
Duration maxDelay = const Duration(seconds: 8),
bool Function(Object error)? shouldRetry,
void Function(int attempt, Object error)? onRetry,
}) async {
assert(maxAttempts >= 1);
Object? lastError;
StackTrace? lastStack;
var delay = initialDelay;
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await operation();
} catch (e, st) {
lastError = e;
lastStack = st;
if (attempt >= maxAttempts) break;
if (shouldRetry != null && !shouldRetry(e)) break;
onRetry?.call(attempt, e);
await Future.delayed(_jittered(delay));
delay = _nextDelay(delay, maxDelay);
}
}
Error.throwWithStackTrace(lastError!, lastStack ?? StackTrace.current);
}