ngCourse2 icon indicating copy to clipboard operation
ngCourse2 copied to clipboard

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

Open adrianmcli opened this issue 7 years ago • 0 comments

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

  • [ ] Edit the code example to show unsubscribing
  • [ ] Edit the plunker to match the example code
  • [ ] Add a paragraph explaining why we are unsubscribing

switchMap

  • [ ] Edit the code example to show unsubscribing
  • [ ] Edit the plunker to match the example code

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

}

adrianmcli avatar Jan 18 '17 20:01 adrianmcli