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();
...
答案 0 :(得分:1)
让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