RxJS is great but it is important you unsubscribe from observables to avoid memory leaks.
Unsubscribe from observables
The pattern I use for unsubscribing from observables is takeUntil(). It looks like this:
myObserverable
.pipe(takeUntil(this.unsubscribeAll))
.subscribe(value => this.myData = value);
This tells myObservable to keep taking values until this.unsubscribeAll emits a value.
Here’s the full example on StackBlitz.
async pipe
There is an easier way to subscribe to an observable in Angular. The async pipe automatically unpacks your data and unsubscribes from the observable when your component is removed from the DOM.
Other articles in this series
- RxJS 6 examples in Angular 6 – Creating observables
- RxJS 6 examples in Angular 6 – Transformation Operators
- RxJS 6 examples in Angular 6 – Filtering Operators
- RxJS 6 examples in Angular 6 – Conditional Operators
- RxJS 6 examples in Angular 6 – Error Handling Operators
- RxJS 6 examples in Angular 6 – Unsubscribe from Observables