Как заменить подписчика на Обозревателя? - PullRequest
0 голосов
/ 02 сентября 2018

Эта проблема на 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();
    ...

1 Ответ

0 голосов
/ 02 сентября 2018

Вместо создания подписки, как вы, позвольте 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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...