2016-07-12 6 views
1

私はAngular 2を初めて使うので、これは簡単かもしれません.2秒ごとに発生するRx.Observableインターバルコールをキャンセルする方法を理解しようとしています。私はこれでRx.Observableを購読する:Rx Observableインターバルコールをキャンセルする

getTrainingStatusUpdates() { 
    this.trainingService.getLatestTrainingStatus('train/status') 
     .subscribe(res => { 
      this.trainingStatus = res; 
      if (this.trainingStatus == "COMPLETED") { 
       //Training is complete 
       //Stop getting updates 
      } 
     }); 
} 

これは私のRx.Observable間隔コールが(これは異なるファイルから上記の関数によって呼び出された)私のservice.tsファイルで処理される方法です。

getLatestTrainingStatus(url: string) { 
    return Rx.Observable 
     .interval(2000) 
     .flatMap(() => this._http.get(url)) 
     .map(<Response>(response) => { 
      return response.text() 
     }); 
} 

サブスクリプションメソッドでわかるように、私は単に 'trainingStatus'が 'COMPLETED'のときにインターバルコールを(2秒ごとに)停止する必要があります。

答えて

2

これは、unsubscribeオプションで可能です。

すべての.subscribe()は、サブスクリプションオブジェクトを返します。このオブジェクトを使用すると、基礎となるObservableの登録を解除できます。

getTrainingStatusUpdates() { 
 
    // here we are assigning the subsribe to a local variable 
 
    let subscription = this.trainingService.getLatestTrainingStatus('train/status') 
 
     .subscribe(res => { 
 
      this.trainingStatus = res; 
 
      if (this.trainingStatus == "COMPLETED") { 
 
       //this will cancel the subscription to the observable 
 
       subscription.unsubscribe() 
 
      } 
 
     }); 
 
}

1
getTrainingStatusUpdates() { 
    this.trainingService.getLatestTrainingStatus('train/status') 
    .do(res => this.trainingStatus = res) 
    .first(res => res == "COMPLETED") 
    .subscribe(/* Do stuff, if any */); 
} 

あなたは間隔を停止/退会する必要はありません。終了時に停止しますres == "COMPLETED"

関連する問題