Understanding the retry Operator

The retry operator behaves much like a standard observable in that it forwards emitted values directly to the observer. The distinction emerges when the source observable encounters an error—instead of passing that error along, retry re-subscribes to the source. The total number of these re-subscriptions is governed by the count argument supplied to the operator.

It's worth noting that the observer sees every value emitted by the source, including those that preceded the failure. To illustrate: if the source first emits {1,2}, then throws an error, and after re-subscription successfully produces {1,2,3,4} before completing, the observer will receive the full sequence {1,2,1,2,3,4}.

Here is the operational flow of retry:

  1. Begin by subscribing to the source observable
  2. Whenever the source emits a value, forward it immediately to the observer
  3. In the event of an error from the source, check how many re-subscriptions have already occurred against the configured retry count
  4. If the retry limit has not been reached, resubscribe to the source; otherwise, emit an error notification to the observer
  5. When the source completes successfully, send a complete notification to the observer

Practical Application

Failures are an inevitable part of software, and RxJS streams are no exception. Network requests, for instance, can fail for a variety of reasons, making a retry mechanism an essential tool in many scenarios.

The retry operator is well-suited for re-attempting a failed network request. However, if your retry logic depends on specific conditions—such as the nature of the error message—you should turn to the retryWhen operator instead.

Consider this example, where retry is employed to make two additional attempts after a request fails:

const url = 'https://i.imgur.com/fHyEMsl.jpg';

fromFetch(url).pipe(
   switchMap((response) => response.json()),
   // triggers 3 network requests:
   // 1 initial and 2 retries
   retry(2)
).subscribe();

Interactive Demo

Further Reading