0

I have a sequial list of observables is requiring sequencial execution (these are in concat operator but I can remove in forkjoin), but when error is happening I need to stop the sequential results. How to abort the remaining observables when any observable is throwing error?

concat( // This could be any operator, the execution should be in requence
   verifyToken,
   // subscribed after first completes
   verifyUser,
   verificationWithError, // Cancel the fourth one because we have error in third observable
   // subscribed after second completes
   checkRoles
)
 .pipe(
   map((printOnlyTheGoodOnes) => {
     return printOnlyTheGoodOnes;
   }),
   catchError((_) => of('no more requests!!!'))
 )
 // should log: 1, 2, 3, 4, 5
 .subscribe(console.log);

sample in stackblitz

Tabares
  • 4,083
  • 5
  • 40
  • 47

1 Answers1

2

You are returning an observable inside an observable in the below two lines. Please change it to

Before:

const error = throwError('This is an error!');
const verificationWithError = of(error);

After:

const verificationWithError = throwError('This is an error!');

Also to get the required output, we need to return EMPTY which completes the observable when there is an error!

const verifyToken = rxjs.of(1, 2, 3);
const verifyUser = rxjs.of(4, 5, 6);
const checkRoles = rxjs.of(7, 8, 9);
const verificationWithError = rxjs.throwError('This is an error!');

rxjs.concat(
    // This could be any operator, the execution should be in requence
    verifyToken,
    // subscribed after first completes
    verifyUser,
    verificationWithError, // Cancel the fourth one because we have error in third observable
    // subscribed after second completes
    checkRoles
  )
  .pipe(
    rxjs.map((printOnlyTheGoodOnes) => {
      return printOnlyTheGoodOnes;
    }),
    rxjs.catchError((_) => rxjs.EMPTY)
  )
  // log: 1, 2, 3, 4, 5, 6, 7, 8, 9
  .subscribe(console.log);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.5.6/rxjs.umd.min.js" integrity="sha512-yUlloKtrX4U41iKbaafsHrrwII0n1uAX9+3KzuaTjkfgLicBplGfr0vv7FtfwC5kgead1Dmr7sjunFFp0a+s9Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Naren Murali
  • 19,250
  • 3
  • 27
  • 54