In Angular 2 are there any specific pitfalls regarding memory management, I should be aware of?
What are the best practices to manage the state of components in order to avoid possible leaks?
Specifically, I've seen some people unsubscribing from HTTP observables in the ngOnDestroy
method. Should I always do that?
In Angular 1.X I know that when a $scope
is destroyed, all listeners on it are destroyed as well, automatically. What about observables in Angular 2 components?
@Component({
selector: 'library',
template: `
<tr *ngFor="#book of books | async">
<td>{{ book.title.text }}</td>
<td>{{ book.author.text }}</td>
</tr>
`
})
export class Library {
books: Observable<any>;
constructor(private backend: Backend) {
this.books = this.backend.get('/texts'); // <-- does it get destroyed
// with the component?
}
};
As requested by @katspaugh
In your specific case there's no need to unsubscribe manually since that's the Async pipe's job.
Check the source code for AsyncPipe. For brevity I'm posting the relevant code
class AsyncPipe implements PipeTransform, OnDestroy {
// ...
ngOnDestroy(): void {
if (isPresent(this._subscription)) {
this._dispose();
}
}
As you can see the Async pipe implements OnDestroy, and when it's destroyed it checks if is there some subscription and removes it.
You would be reinventing the wheel in this specific case (sorry for repeating myself). This doesn't mean you can't/shouldn't unsubscribe yourself in any other case like the one you referenced. In that case the user is passing the Observable between components to communicate them so it's good practice to unsubscribe manually.
I'm not aware of if the framework can detect any alive subscriptions and unsubscribe of them automatically when Components are destroyed, that would require more investigation of course.
I hope this clarifies a little about Async pipe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With