Angular - pipe function break execution flow

Viewed 347

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?

3 Answers

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
})

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();

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();
Related