我对RxJs可观察对象是陌生的,一旦满足条件,我将难以取消订阅循环,请您帮我
在下面的函数中,只要代码到达if块,我都想取消订阅Observables
在问这个问题之前,我先经历了下面的问题,但没有一个对我有太大帮助
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);
}
});
答案 0 :(得分:5)
您可能想要takeWhile
:
this.router.events
.pipe(
takeWhile(url => url === ...), // when the condition isn't met it'll complete immediatelly
)
.subscribe(...);
但是如果您还想包含最后一个值(完成Observable的值),则需要执行以下操作:
this.router.events
.pipe(
concatMap(url => url === ... ? of(url, null) : of(url)),
takeWhile(Boolean),
)
.subscribe(...);
答案 1 :(得分:1)
您可以如下使用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();
}
});