2017-01-09 27 views
1

我想創建一個發出文件添加/刪除(通過chokidar)的observable。我能做到這一點的是這樣的:RxJs - 僅當有用戶時計算併發出數值

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所以我可能會丟失一些顯而易見的解決方案。這可能嗎?

回答

3

你在正確的軌道上。首先,如果您從創建者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(); 
相關問題