dopatraman
dopatraman

Reputation: 13908

How do I detect the completion of a route subscription?

I'm using angular2:

this.route.params.subscribe(params => {
    //do stuff with params
})

I looked at the RxJS docs and it says its possible to add a completion callback:

this.route.params.subscribe(params => {
    // do stuff with params
}, (err) => { throw err;}, () => {
    console.log('Completed!');
});

But this completion is never fired. Is the Angular2 use of Observables different from the norm?

Upvotes: 0

Views: 76

Answers (1)

Steven Luke
Steven Luke

Reputation: 522

There is nothing special in how the ActivatedRoute observables work. You are correct in how you would detect the completion state. But the completion probably never occurs. The completion callback would be called when the Observable executes observer.complete(), which happens when there is a fixed amount of data to send (say iterate over an array, or get a response from some other source). But the Observable on route parameters is indefinite - is is meant to listen for any changes to the parameters that may occur over the life of the component (so the same component can be used to serve different parameter values saving on the time it takes to generate the component). Since those changes can come from the user or from other parts of your app the Observable lasts the lifetime of the component, and the completed callback should not occur. This is why you should unsubscribe from the Observable in your ngOnDesctroy() method (prevent memory leaks from having a hot Observable hanging around).

Upvotes: 1

Related Questions