rangle / ngCourse2

An Angular Course from Rangle.io
Other
184 stars 126 forks source link

Examples in the flatMap and switchMap sections will leave a memory leak #895

Open adrianmcli opened 7 years ago

adrianmcli commented 7 years ago

When using RxJS Observables, one must remember to unsubscribe from your streams if they are infinite value streams. Otherwise, they can hold on to resources and cause a memory leak.

On the other hand, finite value streams automatically terminate, and will not use any resources once the component is destroyed. HTTP requests are an example of finite streams, and since this is a very common usage of RxJS in Angular 2, it can be easy to forget about unsubscribing from infinite value streams.

However, event listeners are infinite value streams, and the examples on the flatMap and switchMap pages will cause a memory leak unless we save the subscription object, and call unsubscribe() on them when we destroy the component (with ngOnDestroy).

Thanks to @housseindjirdeh and @ashwin-sureshkumar for a brief discussion on this topic.

Source: http://stackoverflow.com/questions/38008334/angular2-rxjs-when-should-i-unsubscribe-from-subscription

Proposed Actions

We should probably:

flatMap

switchMap

Example Code

This is a template to work off of:

import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/interval';

@Component({
  selector: 'app-counter',
  template: `<p>This is the counter component.</p>`,
  styles: []
})
export class CounterComponent implements OnDestroy {

  subscription: Subscription;

  constructor() {
    this.subscription = Observable.interval(1000).subscribe(console.log);
  }

  ngOnDestroy() {
    // if you comment this out, you will get a memory leak
    this.subscription.unsubscribe();
  }

}