Exercise - RetryWhen Operator
Exercise
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 aclick
event listener to thebtn
element, and added amap()
operator to return a random integer between10
and15
. - Start by using the
mergeMap()
operator with theajax.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 themap()
operator to return thedata
property from the response object. - Also on the Observable returned from the
ajax.getJSON()
method, use thecatchError()
operator in the event that the Observable emits an error notification. Within thecatchError()
selector function, update theoutput
textarea value to include the error message. You can refer to code in the Observer'snext()
function for this. Finally, use thethrowError()
operator to return an Observable from thecatchError()
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 whosestatus
property is404
to be a failed request. TheretryWhen()
operator is invoked with anotifier
Observable. On thenotifier
Observable use themergeMap()
operator for each notification, and check theindex
of the notification against aMAX_RETRIES
constant value of2
. If both, theindex
is less thanMAX_RETRIES
and the errorstatus
is 404, then return an Observable that emits a next notification ofnull
. Else, return an Observable that emits an error notification. - Finally, use the
finalize()
operator to add thecursor-not-allowed
andopacity-50
classes to thebtn
element.
URL for requests: https://reqres.in/api/users/[id]
.