【问题标题】:Cancelling an Observable mid-chain when a condition is not met不满足条件时取消 Observable 中链
【发布时间】:2020-09-12 22:59:12
【问题描述】:

是否可以取消中链的 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...
);

【问题讨论】:

    标签: angular typescript rxjs ngrx


    【解决方案1】:

    因此您可以为此目的使用filter 运算符:

    observable_1.pipe(
          take(1),
          switchMap((result_1) => {
          }),
          switchMap((result_2) => {
            // If it fails, there is no point to proceed
            result_2.status = false;
            // If it succeeds, we can continue
            result_2.status = true;
            return result_2;
          }),
          filter(result => result.status)
          // etc...
        );
    

    【讨论】:

      【解决方案2】:

      看来你需要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.
      );
      

      【讨论】:

        猜你喜欢
        • 2020-01-11
        • 2019-11-10
        • 2018-03-05
        • 2016-09-25
        • 2019-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多