【问题标题】:How do I replace a subscriber with an Observer?如何用观察者替换订阅者?
【发布时间】:2019-02-07 14:20:36
【问题描述】:

This GitHub 上的问题非常概括。我正在使用 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();
    ...

【问题讨论】:

    标签: node.js angular rxjs


    【解决方案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

    【讨论】:

    • 谢谢 994!现在就像一个魅力! :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    相关资源
    最近更新 更多