このページはまだ翻訳されていないため、英語で表示されます。 翻訳に参加する

fxRetry

Runs a flaky effect again until it succeeds — up to attempts times, with optional backoff between failures.

Future<T> fxRetry<T>(int attempts, FutureOr<T> Function() f, {Duration Function(int failed)? delay, bool Function(Object error)? retryIf, FutureOr<void> Function(Object error, int failed)? onRetry}) FxAsyncIterable<R> fxMapRetryAsync<A, R>(int attempts, FutureOr<R> Function(A a) f, FxAsyncIterable<A> iterable, {Duration Function(int failed)? delay, bool Function(Object error)? retryIf, FutureOr<void> Function(Object error, int failed)? onRetry}) FxAsync<R> Fx<T>.mapRetry<R>(int attempts, FutureOr<R> Function(T a) f, {delay, retryIf, onRetry}) // chain (sync → async) FxAsync<R> FxAsync<T>.mapRetry<R>(int attempts, FutureOr<R> Function(T a) f, {delay, retryIf, onRetry}) // chain (async)

Lecture

Real pipelines call real services, and real services flake. The hand-rolled answer is a for loop with a try/catch, a counter, and a Future.delayed — copied into every project, subtly different each time. fxRetry(attempts, f) is that loop, once: run f, and on error run it again, up to attempts total runs; when the budget is spent the last error rethrows with its original stack trace. The delay hook receives the failure count (1, 2, …), so backoff is one line: delay: (failed) => Duration(seconds: failed).

mapRetry(attempts, f) is the same idea per element: a map whose every call gets its own retry budget. It is built on the parallel-safe fxMapAsync, so under concurrent(n) each in-flight element retries independently — one slow, flaky item re-runs while its neighbors sail through, and order is still preserved. To retry a whole pipeline instead, wrap its terminal: fxRetry(3, () => fxAsync(…).toList()) — the partial result is discarded and the pipeline re-runs from a fresh iterator.

Not every error deserves another run. retryIf receives the error and decides: return false and it rethrows at once — no delay, no attempts spent — so a timeout retries while a 404 or a parse error fails fast. onRetry is called with the error and the failure count for every failure that will be retried, before the delay: the place to log it, or to drop a broken connection before the next run. The final failure is not reported there; it is the error the call completes with. mapRetry takes both, per element.

fxdart extension (no FxTS counterpart), after Rx's retry/retryWhen — re-designed for the pull model, where "resubscribe" means "build the iterable again". For typed failure handling after the retries run out, hand the result to fxEitherCatching.

Demo 1 · A flaky fetch, with backoff

Demo 2 · mapRetry under concurrent

Demo 3 · retryIf and onRetry

Try it yourself

Exercise: make the import survive its flaky rows.

Related: timeout — bound how long each pull may take · concurrent — retries stay independent per in-flight element · typed errors — when the failure should be a value, not an exception