9

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

In the below function if anytime the code reaches the if block I wanted to unsubscribe the 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
  2. AngularJs - RXJS Observable unsubscribe

Javascript Function

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

    }
});
Mahesh G
  • 1,226
  • 4
  • 30
  • 57

2 Answers2

18

You probably want takeWhile:

this.router.events
  .pipe(
    takeWhile(url => url === ...), // when the condition isn't met it'll complete immediately
  )
  .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:

Before RxJS 6.4

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

Since RxJS 6.4

RxJS 6.4 added an overload to takeWhile, it is now possible to include the last value like this:

this.router.events
  .pipe(
    takeWhile(url => url === ..., true),
  )
  .subscribe(...);
martin
  • 93,354
  • 25
  • 191
  • 226
2

You may make use of a Subject and takeUntil operator as follows:

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();
    }
});
siva636
  • 16,109
  • 23
  • 97
  • 135