retryClient<T> function
A client that handles retry logic for a given function.
This client takes RetryOptions and a function to execute. If the function fails, it will be retried according to the specified options. If it succeeds, the result of the function will be returned.
Implementation
FutureOr<T> retryClient<T>({
required RetryOptions options,
required FutureOr<T> Function() fn,
}) async {
const defaultDelay = Duration(seconds: 1);
for (int attempt = 0; attempt < options.maxRetries; attempt++) {
try {
return await fn();
} catch (e) {
final isLastAttempt = attempt == options.maxRetries - 1;
final shouldRetry = await options.retryIf?.call(e) ?? true;
if (isLastAttempt || !shouldRetry) {
rethrow;
}
final duration =
options.delayDurations?[attempt] ?? defaultDelay * pow(2, attempt);
await _delay(duration, attempt, options.addJitter);
}
}
// This line should never be reached
throw StateError('Exhausted all retry attempts');
}