[英]Using Rxjs's `takeUntil` to auto unsubscribe - without waiting for emission?
[英]RxJS takeUntil doesn't unsubscribe
我想使用“ takeUntil”運算符以聲明性樣式退訂。 但這基本上是行不通的。 我仍然可以看到控制台輸出。
const unsubscribe = new Subject();
function printFoo() {
of('foo')
.pipe(takeUntil(unsubscribe))
.subscribe(console.log) // Why I can see 'foo' in the console?
}
function onDestroy() {
unsubscribe.next();
unsubscribe.complete();
}
onDestroy()
setTimeout(() => printFoo(), 200)
StaackBlitz:
https://stackblitz.com/edit/rxjs-svfkxg?file=index.ts
PS我希望即使unsubscribe.next()
也足以取消訂閱,但是即使使用unsubscribe.complete()
也行不通。
您甚至在創建帶有takeUntil
的鏈之前調用onDestroy()
。
當您最終調用printFoo()
,將不再printFoo()
先前要unsubscribe
發射,並且主題unsubscribe
已經完成,因此在這種情況下takeUntil
將永遠不會完成鏈接。
因為主題在printFoo
訂閱之前發出。
訂閱后,不再有主題發射。
您可以改用BehaviorSubject,因為它保存了發出的值(最后發出的值):
const unsubscribe = new BehaviorSubject(false);
function printFoo() {
of('foo')
.pipe(takeUntil(unsubscribe.pipe(filter(value => !!value)))) // Don't unsub if it's false emitted
.subscribe(console.log)
}
function onDestroy() {
unsubscribe2.next(true); // Emit true to cancel subscription
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.