A memory leak is one of the worst types of issues you can have. It’s hard to find, hard to debug, and often hard to solve. Unfortunately, this problem occurs in every programming language or framework, including Angular. Observables are awesome, because of the incessant stream of data, but this benefaction can cause serious problem with memory leak. Today we will take a closer look at the ngOnDestroy Angular hook, and answer the question: “When should I unsubscribe from an observable? What is the best pattern to use?”

In this post we will:

Create an app which generates random numbers.

Reproduce a memory leak in it.

Fix the memory leak with the takeUntil + ngOnDestroy pattern.

To accomplish these tasks, make sure you:

Install Node.js and npm (at the time of writing I am using Node.js v8.11.1 and npm 5.8.0).

Install @angular/cli (in this post I am using version 6.0.0).

Have intermediate knowledge of Angular.

Let’s Create the App

We need to start by initializing a new Angular project. To do that, enter the following commands in your terminal: