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?

3
  • 1
    Don't catch the error? Commented Aug 17, 2021 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. Commented Aug 17, 2021 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. Commented Aug 17, 2021 at 13:48

3 Answers 3

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
})
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.