22

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?
    }
};
Community
  • 1
  • 1
katspaugh
  • 17,449
  • 11
  • 66
  • 103
  • don't forget to unsubscribe from Observable in ngOnDestroy – Mourad Zouabi Dec 25 '15 at 10:57
  • 2
    In your case unsubscribing from the Observable in `ngOnDestroy` is not necessary, the `Async` pipe handle all that for you. That would be a *good practice*, instead of subscribing yourself let the pipe do that everything for you. – Eric Martinez Dec 25 '15 at 11:54
  • @EricMartinez, thanks! I would accept that as the answer (especially if you provide a proof link). – katspaugh Dec 27 '15 at 17:35
  • Does this answer your question? [Is it necessary to unsubscribe from observables created by Http methods?](https://stackoverflow.com/questions/35042929/is-it-necessary-to-unsubscribe-from-observables-created-by-http-methods) – Liam Mar 11 '21 at 14:13

2 Answers2

16

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.

Eric Martinez
  • 31,277
  • 9
  • 92
  • 91
  • Hey @katspaugh I got an answer from Rob and I thought you could be interested on it, check it out here in this [comment](https://gitter.im/angular/angular?at=5681e8ce3c68940269251f9f) – Eric Martinez Dec 29 '15 at 02:17
  • 1
    Check out this [hangout talk](https://www.youtube.com/watch?v=UHI0AzD_WfY) as well (min 27:40), it doesn't go deep on the subject, but I was curious about it because of your question and found out that video. – Eric Martinez Dec 29 '15 at 02:24
  • 3
    Thanks, interesting! So Rob basically says you don't need to unsubscribe from observables that complete with a single value (HTTP requests being an example of those). – katspaugh Dec 29 '15 at 17:21
4

You do not have to unsubscribe from standard subscriptions like after http.get(). But you DO have to unsubscribe from subscription on your custom Subjects. If you have some component and inside it you subscribing to some Subject in your service, then every time you showing that component new subscription will be added to the Subject.

Problems with my service

Please check this out: Good solution to make your components 'clean'

My personal approach - all my components are extended from this nice class:

import { OnDestroy, OnInit } from '@angular/core';
import { Subject } from 'rxjs/Subject';

/**
 * A component that cleans all subscriptions with oneself
 * https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription
 * @class NeatComponent
 */
export abstract class NeatComponent implements OnDestroy, OnInit {
// Add '.takeUntil(this.ngUnsubscribe)' before every '.subscrybe(...)'
// and this subscriptions will be cleaned up on component destroy.

  protected ngUnsubscribe: Subject<any> = new Subject();

  public ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

  public ngOnInit(){}
}

And I just adding super() call to constructor and .takeUntil(this.ngUnsubscribe) before every subscribe:

import { NeatComponent } from '../../types/neat.component';

@Component({
  selector: 'category-selector',
  templateUrl: './category-selector.component.pug'
})
export class CategorySelectorComponent extends NeatComponent {

  public constructor(
    private _shopService: ShopsService
  ) { super(); }

  public ngOnInit() {
    this._shopService.categories.takeUntil(this.ngUnsubscribe)
      .subscribe((categories: any) => {
        // your code here
      })
  }
}
Anton Pegov
  • 1,413
  • 2
  • 20
  • 33