GitHub上的This问题几乎总结了它。我使用timer()
以1秒的重复计划执行某项任务。我将它与Subscriber
配对以订阅间隔。当某个模型用完数据时,我取消订阅并等待新到货。当他们再次填充数据时,我尝试再次订阅但它不起作用。事实证明,当Subscriber
未被取消时,我不能再使用它了。所以我必须用Observer
替换它。这是一个新手,我不知道该怎么做。试着看一些例子,他们只是把我弄糊涂了。
如何使用Observer
替换以下代码?
private timer = timer(1000, 1000);
// A timer subscription that keeps sending new images to the observer
timerSubscription = new Subscriber(() => {
// Check if there is an element in the list
if (this.head != null) {
// If the current node at head is a folder, unsubscribe the listener
if (this.head.data['id'].startsWith('folder')) {
this.timerSubscription.unsubscribe();
}
// Pop a node from the list and pass on to observer
this.observer.next(this.this$PiFrame.pop());
} else {
// If no nodes are left, unsubscribe from the timer
this.timerSubscription.unsubscribe();
console.log('No items left on the queue. Deactivating timer subscription.');
}
}, e => {}, () => {});
我订阅如下:
...
// Setup a timer to pop every 1000 ms
this.timer.subscribe(this.this$PiFrame.timerSubscription);
...
// If no nodes are left, unsubscribe from the timer
this.timerSubscription.unsubscribe();
...
不要像你那样创建订阅,而是让Observable
返回订阅。
将逻辑保留在函数中,如下所示:
doWhatever() {
console.log("tick")
// Check if there is an element in the list
if (this.head != null) {
// If the current node at head is a folder, unsubscribe the listener
if (this.head.data['id'].startsWith('folder')) {
this.timerSubscription.unsubscribe();
}
// Pop a node from the list and pass on to observer
this.observer.next(this.this$PiFrame.pop());
} else {
// If no nodes are left, unsubscribe from the timer
this.timerSubscription.unsubscribe();
console.log('No items left on the queue. Deactivating timer subscription.');
}
}
然后,当你想订阅时:
this.timerSubscription = this.timer.subscribe(() => this.doWhatever());
这可以重复使用,因为每个subscribe
生成一个新的Subscription