I've already read Ben's article regarding unsubscribing via , takeUntil
, takeWhile
( the predicate version )
I've used it like this example in my Angular app
But there is something which I don't understand.
Say I have an Observable which emit values after a long time :
const source = Rx.Observable.interval(10000);
var isContinue=true;
const example = source.takeWhile(val => isContinue)
.subscribe(val => {},()=>{},()=>console.log('complete'));
setTimeout(function (){isContinue=false},3000) //somewhere in destructor
Well , this will show "complete" only after 10 seconds and not after 3.
So basically if I have a component which subscribes to an Observable and that observable doesn't emit values for a long time , it will still have a reference to my object , causing slow memory leaks.
Question:
How can I use the takeWhile operator to unsubscribe as soon as I set the isContinue
value.
I don't want to trust a service which may not emit values and to keep a reference to my component.
I believe your code produces the correct emissions - but your concern is the timeliness of the completion (it should complete after 3 seconds, not 10 seconds).
It takes 10 seconds as takeWhile
only tests its predicate when the source observable emits.
takeUntil
will fix this, but it needs an observable to wait on:
const source = Rx.Observable.interval(10000);
const abort = new Subject();
const example = source.takeUntil(abort)
.subscribe(val=>{}, ()=>{}, ()=>console.log('complete'));
setTimeout(function () {abort.next()}, 3000) //somewhere in destructor
您需要将isContinue
变量设置为Observable
并订阅两个observables: source
和isContinue
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.