Roka545
Roka545

Reputation: 3626

Cancel an Rx Observable interval call

I'm new to Angular 2 so maybe this is trivial - I'm trying to figure out how to cancel an Rx.Observable interval call that happens every 2 seconds. I subscribe to the Rx.Observable with this:

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

This is how my Rx.Observable interval call is handled in my service.ts file (this is called by the function above from a different file):

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

As you can see in the subscription method, I simply want to stop the interval calls (every 2 seconds) when 'trainingStatus' is 'COMPLETED'.

Upvotes: 3

Views: 7348

Answers (2)

Can Nguyen
Can Nguyen

Reputation: 1470

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

You don't have to unsubscribe / stop the interval. It will be stopped when res == "COMPLETED"

Upvotes: 2

Daniel Pliscki
Daniel Pliscki

Reputation: 1923

That's possible with the unsubscribe option.

Every .subscribe() returns a subscription object. This object allows you to unsubscribe to the underlying 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()
            }
        });
}

Upvotes: 6

Related Questions