代码之家  ›  专栏  ›  技术社区  ›  Mahesh G

如何在RXJS中满足条件后立即取消订阅

  •  2
  • Mahesh G  · 技术社区  · 7 年前

    我刚接触到RXJS观测仪,我发现一旦达到标准就很难取消订阅循环,你能帮我吗?

    在下面的函数中,如果代码到达if块,我想取消订阅观察项

    在问这些问题之前,我已经回答了下面的问题,但没有一个对我有很大帮助。

    1. Rxjs observable wait until some condition is met
    2. AngularJs - RXJS Observable unsubscribe

    javascript函数

    this.router.events.subscribe((url: any) => {
        url = this.router.url;
        if ((url === "/profile" || url === "/summary") && this.filterConfigFlag === false) {
    
            /*
            Perform operations
            */
    
        } else {
            console.log(typeof (url), url);
    
        }
    });
    
    2 回复  |  直到 7 年前
        1
  •  5
  •   martin    7 年前

    takeWhile

    this.router.events
      .pipe(
        takeWhile(url => url === ...), // when the condition isn't met it'll complete immediatelly
      )
      .subscribe(...);
    

    this.router.events
      .pipe(
        concatMap(url => url === ... ? of(url, null) : of(url)),
        takeWhile(Boolean),
      )
      .subscribe(...);
    
        2
  •  1
  •   siva636    7 年前

    Subject takeUntil

    unsubscribe = new Subject<any>();
    
    this.router.events.pipe(takeUntil(unsubscribe)).subscribe((url: any) => {
        url = this.router.url;
        if ((url === "/profile" || url === "/summary") && this.filterConfigFlag === false) {
    
            /*
            Perform operations
            */
    this.unsubscribe.next();
        } else {
            console.log(typeof (url), url);
    this.unsubscribe.next();
        }
    });