不能停止可观察间隔
我已经尝试过几乎所有可以找到的东西,并且似乎无法获取此间隔以停止执行订阅中的代码。我使用间隔错误?不能停止可观察间隔
var subject = new Subject();
var interval = Observable.interval(this.settings.timing * 1000);
var subscription = interval
.takeUntil(subject)
.subscribe(t => {
console.log('pushing new item');
this.activeItems[0].contentLeaving = true;
setTimeout(()=>{
this.activeItems[0].imageLeaving = true;
setTimeout(()=>{
this.activeItems.push(this.activeItems.shift());
setTimeout(()=>{
this.activeItems[1].contentLeaving = false;
this.activeItems[1].imageLeaving = false;
},510);
},510);
},510);
});
this.moduleProps.intervals.push(subject);
在我ngOnDestroy
this.moduleProps.intervals.forEach((i)=>{
i.complete();
});
但毕竟这发生了,我仍然看到控制台日志声明,称“推新项目”,如果它仍然在我的区间运行。
根据本文档(https://www.learnrxjs.io/operators/filtering/takeuntil.html),takeUntil发射直到提供的observable发射。你正在完成观察而不发射任何东西。尝试将.next()添加到您的onDestroy方法中。
this.moduleProps.intervals.forEach((i)=>{
i.next(); // have subject emit
i.complete();
});
这里是一个工作普拉克(https://plnkr.co/edit/Zdf8C9d8vHk84uIMYHvH?p=preview)
尝试.takeWhile
而不是.takeUntil
,它可以使用一个布尔值。
private finished = false; // component property
var interval = Observable.interval(this.settings.timing * 1000);
var subscription = interval
.takeWhile(_ => this.finished)
.subscribe(t => {
...
的OnDestroy是那么简单this.finished = true;
takeWhile接受一个函数,假设返回一个布尔值,而不仅仅是一个布尔值 – LLai
确实,正在纠正...... –
你可以叫'subscription.unsubcscribe()''内部认购()'。或者,也许我不明白你想要做什么... – martin