LiveLoveApp logo

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.

  1. Open exercise on codesandbox. I've already imported the necessary functions from rxjs. Also, I've already used the fromEvent() operator to add a click event listener to the btn element, and added a map() operator to return a random integer between 10 and 15.
  2. 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.
  3. On the Observable returned from the ajax.getJSON() method use the map() operator to return the data property from the response object.
  4. 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 output textarea 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.
  5. Next, use the retryWhen() operator to retry a failed request up to 2 additional times. In this exercise, we'll consider a response whose status property is 404 to be a failed request. The retryWhen()operator is invoked with a notifier Observable. On the notifier Observable use the mergeMap() operator for each notification, and check the index of the notification against a MAX_RETRIES constant value of 2. If both, the index is less than MAX_RETRIES and the error status is 404, then return an Observable that emits a next notification of null. Else, return an Observable that emits an error notification.
  6. Finally, use the finalize() operator to add the cursor-not-allowed and opacity-50 classes to the btn element.

URL for requests:[id].