gpt4 book ai didi

node.js - 如何用观察者替换订阅者?

转载 作者:太空宇宙 更新时间:2023-11-04 00:06:18 26 4
gpt4 key购买 nike

This GitHub 上的问题几乎概括了这一点。我使用 timer() 和 1 秒的循环计划来执行特定任务。我将其与订阅者配对以订阅间隔。当某个模型的数据耗尽时,我会取消订阅它并等待新的到来。当他们的数据再次填充时,我尝试再次订阅,但它不起作用。事实证明,当订阅者被取消订阅时,我无法再次使用它。所以我必须用观察者来替换它。我是新手,不知道该怎么做。尝试查看示例,它们只是让我更加困惑。

如何替换以下代码以使用 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());

这可以重复使用,因为每个订阅都会生成一个新的订阅

关于node.js - 如何用观察者替换订阅者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52134280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com