2

I have below code:

 subscriber.pipe(
       switchMap(data => {
          this.getData().pipe(
             map(() => res),
             catchError(error => {
                 return of(null);
             })
          );
       }),
       switchMap(data => {
    
       })
    
    ).subscribe();

In case of error in first switchMap i am returning of(null) so next switchMap is reciving data as null. But i like to stop the execution in case first switchMap goes to catchError block, it should not execute second switchMap. Is there a way to achieve this?

Naveen
  • 773
  • 3
  • 17
  • 40
  • 1
    _Don't_ catch the error? – jonrsharpe Aug 17 '21 at 12:36
  • I also needed to display a error message i missed in the code snippet, i added catchError block at the end like Tobias suggested. – Naveen Aug 17 '21 at 12:50
  • In the example you weren't using `error`, note you can also use `throwError` if you actually have something to do in the `catchError` but want the overall result to be unchanged. – jonrsharpe Aug 17 '21 at 13:48

3 Answers3

4

Put the catchError at the end of the pipe.

subscriber.pipe(
   switchMap(data => {
       ...
   }),
   switchMap(data => {
       ...
   }),
   catchError(error => {
       return of(null);
   })
).subscribe(val => {
    // val will be null if any error happened
})
Tobias S.
  • 21,159
  • 4
  • 27
  • 45
1

I think you can use filter here. from catch error you can return null and after the first switchMap you can use a filter to filter out null.

subscriber.pipe(
       switchMap(data => {
          this.getData().pipe(
             map(() => res),
             catchError(error => {
                 return null;
             })
          );
       }),
       filter(v => v),
       switchMap(data => {
    
       })
    
    ).subscribe();
JsNgian
  • 795
  • 5
  • 19
1

RxJS # EMPTY

EMPTY is an observable that emits nothing and completes immediately.

subscriber.pipe(
       switchMap(data => {
          this.getData().pipe(
             map(() => res),
             catchError(_ => EMPTY)
          );
       }),
       switchMap(data => {
    
       })
    
    ).subscribe();
Mrk Sef
  • 7,557
  • 1
  • 9
  • 21