Lessons36. retry: re-run the source after an error
Lessons · 36
36. retry: re-run the source after an error
retry — try again on error
Networks are flaky: sometimes a request fails "by chance." retry(N) tells RxJS: "if the stream failed, try N more times." N is the number of additional attempts, not counting the first.
source$.pipe(retry(2))
// Attempt 1: error → attempt 2: error → attempt 3: success → pass it on
// If all three fail — the error goes to the subscriber
How retry does it
On an error, retry simply re-subscribes to the original Observable. That means all of the source's work runs again — including the HTTP request, the side effects, and the logs.
When not to
Don't automatically repeat operations that make no sense without user confirmation (a payment, for example). And don't use retry for permanent errors (404, 401) — you'd just waste resources. For a smart retry with a delay and a condition, there's retry({delay, count}).
Your task
- In
pipe, addretry(2). - The source fails the first two attempts and returns
Successon the third. - Expected output:
Attempt: 1 → Attempt: 2 → Attempt: 3 → Success.
Solution spoiler · click to reveal
const { Observable, retry } = Rx;
let attempts = 0;
const source$ = new Observable(subscriber => {
attempts++;
console.log('Attempt: ' + attempts);
if (attempts <= 2) {
subscriber.error('Temporary error');
return;
}
subscriber.next('Success');
subscriber.complete();
});
const result$ = source$.pipe(
retry(2)
);
result$.subscribe({
next: value => console.log(value),
error: error => console.log('Final Error: ' + error),
}); script.ts
CONSOLE · Console output
Hit Run to see the result...