Search code examples
angulartypescriptionic-frameworkrxjs

RxJS catchError to handle caught$ to retry 2 times


Here I need to caught$ to retry 2 times and after that show the error message and throwError(err). Please let me know how to do that here.

this.locationChanged$ = this.locationsService
      .getLocationById()
      .pipe(
        catchError((err,caught$) => {
          //how to retry 2 times here

          // after that this workflow
          console.log(err);
          return throwError(err);
        }),
        retry(2),
        finalize(() => {
         //code
        })
      );

When I do like so above it logs the console.log(err); also 3 times. So how can I avoid that? i.e. I need to do that only once.


Solution

  • As mentioned in the comment, the operator order affects the behaviour of the chain. Each operator modifies the observable and returns the modified observable to the next opeartor.

    For the retry(2) to be triggered before the catchError opeartor, it must be above the catchError operator.

    Try the following

    this.locationChanged$ = this.locationsService
      .getLocationById()
      .pipe(
        retry(2),                       // <-- before `catchError`
        catchError((err,caught$) => {
          console.log(err);
          return throwError(err);
        }),
        finalize(() => {
          //code
        })
      );