Prevent memory leaks in Angular 2? Prevent memory leaks in Angular 2? angularjs angularjs

Prevent memory leaks in Angular 2?


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.


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(){}}