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 aclickevent listener to thebtnelement, and added amap()operator to return a random integer between10and15. - 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 thedataproperty 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 theoutputtextarea 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 whosestatusproperty is404to be a failed request. TheretryWhen()operator is invoked with anotifierObservable. On thenotifierObservable use themergeMap()operator for each notification, and check theindexof the notification against aMAX_RETRIESconstant value of2. If both, theindexis less thanMAX_RETRIESand the errorstatusis 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-allowedandopacity-50classes to thebtnelement.
URL for requests: https://reqres.in/api/users/[id].