RxJs - 计算&仅在有订户时才发出值

时间:2017-01-09 21:12:27

标签: rxjs rxjs5

我想创建一个可以发出文件添加/删除的observable(通过chokidar)。我可以通过以下方式做到这一点:

Rx.Observable.create((subscriber) => {
  this.watcher = chokidar.watch(
     this.contentPath
  );
  this.watcher.on('addDir', () => { subscriber.next(); });
  this.watcher.on('unlinkDir', () => { subscriber.next(); });
});

我想要做的是,我想停止来观看文件,如果没有订阅者,并在订阅它时重新开始。像这样的东西,但是使用RxJs:

class Notifier {
  constructor() {
    this.subscriberCount = 0;
  }

  subscribe(onNext, onError, complete) {
    this.subscriberCount++;
    if (this.subscriberCount === 1) {
      this.startInternalWatcher();
    }
    return () => {
      this.subscriberCount--;
      if (this.subscriberCount === 0) {
        this.stopInternalWatcher();
      }
    }
  }
}

// files are not watched
const n = new Notifier();

const s1 = n.subscribe(() => {}) // files are being wacthed
const s2 = n.subscribe(() => {}) // files are being wacthed
s1() // unsubscribed from 1, files are still watched.
s2() // unsubscribed from 2, files are not watched because no one is interested in.

我是RxJs的新手,所以我可能会错过一些明显的解决方案。这可能吗?

1 个答案:

答案 0 :(得分:4)

你走在正确的轨道上。首先,如果您从创建者it will be called when the subscription is cancelled返回一个函数,那么您可以使用它来销毁观察者。

这应该解决你的大多数问题,但是如果你想确保最多只有一个观察者"有一段时间你可以使用refCount

return Rx.Observable.create((subscriber) => {
  this.watcher = chokidar.watch(
     this.contentPath
  );
  this.watcher.on('addDir', () => { subscriber.next(); });
  this.watcher.on('unlinkDir', () => { subscriber.next(); });

  return () => this.watcher.off('addDir unlinkDir');
})
.publish()
.refCount();