public function(id: number) {
this.periodicCheckTimer = Observable.timer(10000, 5000).subscribe(
() => {
let model = this.find(id);
if (model['isActivated']) {
this.periodicCheckTimer.unsubscribe();
}
});
}
我想在5分钟后自动停止计时器,如果条件 if(模型[' isActivated'])不满足。但是如果条件满足,我可以手动停止。在这种情况下,不确定手动停止是否仍然正确。
任何有关其他计时器功能的建议也值得赞赏。
答案 0 :(得分:4)
我没有对它进行测试,但是在5mn之后,这里有一个替代你的提议:
function (id: number) {
// emit a value after 5mn
const stopTimer$ = Observable.timer(5 * 60 * 1000);
Observable
// after 10s, tick every 5s
.timer(10000, 5000)
// stop this observable chain if stopTimer$ emits a value
.takeUntil(stopTimer$)
// select the model
.map(_ => this.find(id))
// do not go further unless the model has a property 'isActivated' truthy
.filter(model => model['isActivated'])
// only take one value so we don't need to manually unsubscribe
.first()
.subscribe();
}