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

かの条件場合(モデル[「isActivated」])Observable.Timer()または自動的に一定期間後にObservable.Intervalを()を停止しますが満足されていません。しかし、条件が満たされたら、私はそれを手動で止めることができます。この場合手動停止がまだ正しいかどうかはわかりません。は、どのように私は、私は5分後に自動的にタイマーを停止したい

他のタイマー機能についてのご意見もありがとうございます。

答えて

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()が観測返さ何?私がthis.find(id).subscribe()のように関数を呼び出すのは1回だけです。 –

+0

'find'がobservableを返す場合は、' switchMap'を使用して自分でそれを購読するのではなく、 'switchMap'があなたのためになります。 – Maxime

+1

takeUntil()は私が探していた関数でした。ありがとう!!あなたの答えを提示した感謝しています。 –

関連する問題