angulartypescriptrxjsobservableangular-observable

Observable stops firing even when catching the error


I'm facing with a very strange behavior on my project, I have a simple Angular service with the below code:

seatClick$ = new Subject<Seat>();

and a method on the service that fires the observable:

  handleSeatClick(seat: Seat) {
    this.seatClick$.next(seat);
  }

the observable logic is simple:

this.seatClick$.pipe(
    exhaustMap((seat: Seat) => {
       this.someFunctionThatThrowsException(); // this function throws ref exception
      return of(null);
    })
    , catchError(err => {
        console.log('error handled');
        return of(null);
    })
)
.subscribe(() => {
    console.log('ok');
  },
  (error1 => {
    console.log('oops');
  })
);

This is really strange, when "someFunctionThatThrowsException" is called it throws some ReferenceError exception, this exception is then catched with the catchError and the next() event is fired.

However, from this moment on the seatClick observable stops responding, as if it was completed, calling handleSeatClick on the service won't respond any more.

What am I missing here?


Solution

  • That's correct behavior, you need repeat operator here to resubscribe.

    this.seatClick$.pipe(
        exhaustMap((seat: Seat) => {
           this.someFunctionThatThrowsException();
           return of(null);
        })
    
        // in case of an error the stream has been completed.
        , catchError(err => {
            console.log('error handled');
            return of(null);
        })
    
        // now we need to resubscribe again
        , repeat() // <- here
    )
    .subscribe(() => {
        console.log('ok');
      },
      (error1 => {
        console.log('oops');
      })
    );
    

    also if you know that something might fail you can dedicate it to an internal stream and use catchError there, then you don't need repeat.

    this.seatClick$.pipe(
      // or exhaustMap, or mergeMap or any other stream changer.
      switchMap(seal => of(seal).pipe(
        exhaustMap((seat: Seat) => {
           this.someFunctionThatThrowsException();
           return of(null);
        })
        , catchError(err => {
            console.log('error handled');
            return of(null);
        })
      )),
      // now switchMap always succeeds with null despite an error happened inside
      // therefore we don't need `repeat` outside and our main stream
      // will be completed only when this.seatClick$ completes
      // or throws an error.
    )
    .subscribe(() => {
        console.log('ok');
      },
      (error1 => {
        console.log('oops');
      })
    );