Some weeks ago, I posted about how to handle errors in RxJs. In some cases, it might be a good idea to retry
an Observable when it fails, especially for HTTP requests.
The retry
operator has the following marble diagram:
In the above marble diagram, we retry the Observable 2 times. Since all attempts fail (the X in the timeline indicates an error), we still end up with an error at the end, but we can see that the first and second errors were invisible to the subscriber thanks to the retry
operator.
The nice thing about retry
is that we can specify a delay before retrying, as well as how many times to try again. By default, if we don’t use any parameter, retry
will keep trying forever:
In the above example, we would retry a maximum of 3 times, wait 5 seconds between each attempt, and reset our retry counter if the Observable ends up succeeding. That way, another request in the future would still get all 3 attempts, for instance.
If you’re interested in a slightly more complex example using several more operators, I wrote that tutorial “How to do polling with RxJs and Angular?” that uses the retry
operator.