[Fixed] How to keep observable alive after error in RxJS 6 and Angular 6

Issue

Can anyone help with the scenario where this._getReactions$.next() not working whenever this.http.get(...) gets an error. I want to keep observable alive to take the next input.

private _getReactions$: Subject<any> = new Subject();

 constructor() {
  this._getReactions$
  .pipe(
    switchMap(() => {
        return this.http.get(...)
        // http request 
    }),
    catchError(error => {
      console.log(error);
      return empty();
    })
  )
  .subscribe(data => {
      console.log(data)
      //results handling
  });
 }
onClick() {
  this._getReactions$.next();
}

Solution

If observable dies it calls it error handler and they are closed you can’t send anything through them that means they are closed everything upstream from that including the interval is dead.

what if we want to live.

sheilding the main observer chain is the solution

put catch inside of switchmap
whenever a request is fired switchmap
creates the ajax observable and this time with the
catch.
switchmap has a behavior that it says my source
is not completed yet so I don’t really care if the child
completes I gonna keep going.

 constructor() {
  this._getReactions$
    .pipe(tap(value => { this.loading = true; return value }),
      switchMap(() => {
        return this.http.get(...).pipe(
          catchError((error) => this.handleError(error)))
        // http request
      }),
    )
    .subscribe(data => {
      console.log(data)
      //results handling
      this.error = false;
      this.loading = false
    });
}

private handleError(error: HttpErrorResponse) {

  this.error = true;
  console.log(error)
  this.loading = false
  return empty();

Live Demo

Detailed Info

PS: nesting within any flattening operator, such as mergeMap, concatMap, exhaustMap and other flattening operators would also work.

Leave a Reply

(*) Required, Your email will not be published