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
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);
}
});
Unsubscribing Manually RxJS provides us with a convenient method to do this. It lives on the Subscription object and is simply called . unsubscribe() .
complete() after it has emitted all of it's values. There's no need to unsubscribe. It completes on it's own, which means it unsubscribes all subscribers automatically.
Last but not least step is to trigger unsubscribe$ during the ngOnDestroy . We call . next() method to trigger new value emission and . complete() to automatically unsubscribe all the observers.
Completion. A fundamental aspect of observables is that when they complete, any subscriptions are automatically unsubscribed. As such, if you know an observable will complete then you do not need to worry about cleaning up any subscriptions.
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:
this.router.events
.pipe(
concatMap(url => url === ... ? of(url, null) : of(url)),
takeWhile(Boolean),
)
.subscribe(...);
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(...);
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();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With