2017-03-02 1612 views
0
public function(id: number) { 
    this.periodicCheckTimer = Observable.timer(10000, 5000).subscribe(
     () => { 
      let model = this.find(id); 
      if (model['isActivated']) { 
      this.periodicCheckTimer.unsubscribe(); 
      } 
     }); 
    } 

我想在5分鐘後自動停止計時,如果條件如果(模型[「isActivated」])不滿意。但是,如果條件滿足,我可以手動停止它。在這種情況下,不確定手動停止是否仍然正確。如何停止Observable.Timer()或Observable.Interval()一定時間後自動

與其他計時器功能的任何建議也表示讚賞。

回答

3

我沒有測試出來,但這裏有一個替代你的建議與5MN後停止:

function (id: number) { 
    // emit a value after 5mn 
    const stopTimer$ = Observable.timer(5 * 60 * 1000); 

    Observable 
    // after 10s, tick every 5s 
    .timer(10000, 5000) 
    // stop this observable chain if stopTimer$ emits a value 
    .takeUntil(stopTimer$) 
    // select the model 
    .map(_ => this.find(id)) 
    // do not go further unless the model has a property 'isActivated' truthy 
    .filter(model => model['isActivated']) 
    // only take one value so we don't need to manually unsubscribe 
    .first() 
    .subscribe(); 
} 
+0

如果有什麼功能find()方法返回觀察到的?就像我做了這個.find(id).subscribe()它只調用一次函數。 –

+0

如果'find'返回一個observable,則使用'switchMap',這樣你就不會自己訂閱它,但'switchMap'會爲你做。 – Maxime

+1

明白了! takeUntil()是我正在尋找的功能。謝謝!!讚賞你提出你的答案的方式。 –

相關問題