简体   繁体   English

在RxJs中满足条件后如何立即退订

[英]How to unsubscribe immediately after the the condition is met in RxJs

I am new to the RxJs observables and I am finding difficulty in unsubscribing the loop once the criteria are met, can you please help me 我是RxJ观察站的新手,一旦满足条件,我将难以取消订阅循环,请您帮我一下

In the below function if anytime the code reaches the if block I wanted to unsubscribe the Observables 在下面的函数中,如果代码到达if块,我想退订Observables

Before asking this questions I have gone through below questions and none of them helped me much 在问这个问题之前,我先经历了以下问题,但没有一个对我有太大帮助

  1. Rxjs observable wait until some condition is met Rxjs可观察到,直到满足某些条件
  2. AngularJs - RXJS Observable unsubscribe AngularJs-RXJS可观察的退订

Javascript Function 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);

    }
});

You probably want takeWhile : 您可能想要takeWhile

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

but if you want to include also the last value (the value that completed the Observable) you'll need to do something like this: 但如果您还想包含最后一个值(完成Observable的值),则需要执行以下操作:

this.router.events
  .pipe(
    concatMap(url => url === ... ? of(url, null) : of(url)),
    takeWhile(Boolean),
  )
  .subscribe(...);

You may make use of a Subject and takeUntil operator as follows: 您可以如下使用SubjecttakeUntil运算符:

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();
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM