Exercise - RetryWhen Operator
In this example we are going to retry a network request when the response status code is 404. In a more realistic example we would likely check for a different status code, such as a 500.
Similar to the previous exercise for the
retry() operator we will fetch a random user from the API.
This time, when the user attempts to retrieve a user that does not exist, for the purpose of this example, we'll retry the request 2 additional times.
- Open exercise on codesandbox.
I've already imported the necessary functions from rxjs.
Also, I've already used the
fromEvent()operator to add a
clickevent listener to the
btnelement, and added a
map()operator to return a random integer between
- Start by using the
mergeMap()operator with the
ajax.getJSON()method to fetch a random user from the API. Below you'll find the URL for the GET request.
- On the Observable returned from the
ajax.getJSON()method use the
map()operator to return the
dataproperty from the response object.
- Also on the Observable returned from the
ajax.getJSON()method, use the
catchError()operator in the event that the Observable emits an error notification. Within the
catchError()selector function, update the
outputtextarea value to include the error message. You can refer to code in the Observer's
next()function for this. Finally, use the
throwError()operator to return an Observable from the
catchError()selector function that immediately emits an error notification.
- Next, use the
retryWhen()operator to retry a failed request up to 2 additional times. In this exercise, we'll consider a response whose
404to be a failed request. The
retryWhen()operator is invoked with a
notifierObservable. On the
notifierObservable use the
mergeMap()operator for each notification, and check the
indexof the notification against a
MAX_RETRIESconstant value of
2. If both, the
indexis less than
MAX_RETRIESand the error
statusis 404, then return an Observable that emits a next notification of
null. Else, return an Observable that emits an error notification.
- Finally, use the
finalize()operator to add the
opacity-50classes to the
URL for requests: