取消 Rx Observable 的定时器调用

3

我是Angular 2的新手,也许这很简单 - 我正在尝试找出如何取消每2秒发生一次的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 interval 调用在 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个回答

6

使用取消订阅选项可以实现这一点。

每个 .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()
            }
        });
}


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

您不需要取消订阅/停止间隔。当 res == "COMPLETED" 时,它将停止。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接