Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 - Best way to terminate a observable interval when path changes

I am using an observable interval to execute an certain function every fifth second within a certain component, related to a path in my route configuration.

Observable.interval(5000).subscribe(res => {
    // Something happens here
});

However I want to terminate the interval when the path changes. Now it just continues to execute the task...

What is the best way to do this?

like image 665
Valdemar Edvard Sandal Rolfsen Avatar asked Apr 30 '16 13:04

Valdemar Edvard Sandal Rolfsen


1 Answers

You could unsubscribe from the subscription (the return object of the subscribe method) in such case:

var subscription = Observable.interval(5000).subscribe(res => {
    // Something happens here
});

// to be called when the route changes
subscription.unsubscribe();

Because the observable is cold and there will no more subscription, the observable will be disposed...

You can leverage the "routerOnDesactivate" hook method in your component to unsubscribe. It's the hook that let you know when you leave the route component within the routing context.

See this link for more details:

  • https://angular.io/docs/ts/latest/api/router/OnDeactivate-interface.html
like image 184
Thierry Templier Avatar answered Oct 18 '22 19:10

Thierry Templier