当条件不满足时取消 Observable 中链

Pha*_*aze 5 rxjs typescript ngrx angular

是否可以在链中取消 Observable?假设我们有一些相互依赖的事件链,如果其中一个事件链失败,则无需继续。

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...
);
Run Code Online (Sandbox Code Playgroud)

sat*_*ime 1

看起来你需要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.
);
Run Code Online (Sandbox Code Playgroud)