代码之家  ›  专栏  ›  技术社区  ›  simonberry

取消RXJS FlatMap链上的订阅

  •  1
  • simonberry  · 技术社区  · 8 年前

    对于我的大多数RxJs订阅,我遵循 takeWhile 取消订阅的方法,如中所述 this article by Brian Love

    如果我使用 flatMap ,我应该有多个 花些时间 s(链中的每一个“跳”一次?还是一次 花些时间 足够例如:

      this.dataService.awaitSomeObservable()
          .takeWhile(() => this.alive) /// <= No 1
          .flatMap(result1 => {
    
            //...
    
            return this.dataService.awaitAnotherObservable();
          })
          .takeWhile(() => this.alive) /// <= No 2 - is this necessary ????
          .subscribe(result2 => {
    
              //...
    
            }
          });
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   siva636    8 年前

    takeWhile 应该足够了,但你可以 pipe 如果您使用RxJS的最新版本(v5.5及以上版本),那么它(如下所示)。

    this.dataService.awaitSomeObservable().pipe(
          takeWhile(() => this.alive), 
          flatMap(result1 => {
            //...
            return this.dataService.awaitAnotherObservable();
          })
    ).subscribe(x=>{})
    

    你可以把 花些时间 flatMap ,但提供适当的函数作为 花些时间 基于你的实际用例。