Repeat and Retry HTTP Requests Using RxJS

Netanel Basal
Netanel Basal
Published in
2 min readNov 1, 2022

Sometimes we have to perform a certain operation repeatedly over time, with a set period of time between runs. The most common examples are when we need to poll a server to determine whether the operation succeeded or auto-refresh a stale screen with new data.

The implementation of this functionality becomes a breeze in RxJS version 7. We can use the repeat() operator utilizing the new delay option in v7.5.0. As an example, suppose we want to display the latest metrics to our users every 30 seconds:

The source observable will repeat forever until explicitly destroyed, with a 30 seconds delay between repetitions. In addition, we can also use the count option, which is the number of times to repeat the source.

Let’s say we have a case where we perform some actions requiring polling from the server until we get the status completed:

The delay option also accepts a function that provides the number of times the source has been subscribed to, with the return value being an observable input that indicates when the source should be repeated.

By selecting this option, we can set a delay that increases by one second after each repetition:

The repeat() operator is useful when the source has been completed. We can use the retry() operator to handle errors. As of v7.3.0, we can use the delay option to handle retries with delay and implement exponential backoff quickly.

Exponential backoff is a standard error-handling strategy. In this approach, a client periodically retries a failed request with increasing delays between requests. Here are a few variations we can use:

Follow me on Medium or Twitter to read more about Angular and JS!

--

--

Netanel Basal
Netanel Basal

Written by Netanel Basal

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.

Responses (2)