TypeScript Question

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?

Answer

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:

Comments