Search code examples
angulartypescriptrxjsngrx

Cancelling an Observable mid-chain when a condition is not met


Is it possible to cancel an Observable in mid-chain? Suppose we have some chain of events that depend on each other and if one chain fails, there's no need to continue.

observable_1.pipe(
  take(1),
  switchMap((result_1) => {
    // Do something that requires observable_1 and return something
    // If it fails, there is no point to proceed
    // If it succeeds, we can continue
  }),
  switchMap((result_2) => {
    // Do something that requires result_2 and return something
    // If it fails, there is no point to proceed
    // If it succeeds, we can continue
  }),
  // etc...
);

Solution

  • Looks like you need EMPTY.

    observable_1.pipe(
      take(1),
      switchMap((result_1) => {
        // doing something
        if (successful) {
          return of(result_2);
        }
        return EMPTY; // no further emits.
      }),
      // we are here only in cases of result_2. EMPTY won't trigger it.
      switchMap((result_2) => {
        // doing something
        if (successful) {
          return of(result_3);
        }
        return EMPTY; // no further emits.
      }),
      // we are here only in cases of result_3. EMPTY won't trigger it.
    );