Use Rxjs takeUntil to unsubscribe
Published: 2021-03-19 11:58:32

## Why do we need to **Unsubscribe**?

The subscription will keep reference the component instance **even after** the component is destroyed if you DO NOT unsubscribe in some cases.

So, you have a piece of memory that is not be garbage collected (Memory leak).

Not Good. The app will slow down if we do a lot of this kind of thing.

## Angular will help us to unsubscribe?

Yes, as I know, these are cases:

- `AsyncPipe`
- `HTTP` service
- `timer` observable

Let me know if you know more cases :)

## So, we need to unsubscribe on other cases

---

### 1. The more straightforward way:

You make a subscription, and you shall unsubscribe it.

```typescript
export class MyClass implements OnInit, OnDestroy {
  private subscription: Subscription;
  timer$: Observable<number>;

  ngOnInit() {
    this.subscription = this.timer$.subscribe(t => console.log(t);
    )
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

```

**Pro?** Easy to understand.
**Con?** You or others who work on the same code base might forget to unsubscribe.

### 2. The `takeUntil` way

```typescript
export class MyClass implements OnInit, OnDestroy {
  private readonly unsubscribe$: Subject<void> = new Subject();
  timer$!: Observable<number>;

  ngOnInit() {
    this.timer$
      .pipe(takeUntil(this.unsubscribe$))
      .subscribe((t) => console.log(t));
  }

  ngOnDestroy() {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }
}

```

### What `takeUntil` do?

I think this picture said it all!

![https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pbwc4st2zdder5q7f0e8.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pbwc4st2zdder5q7f0e8.png)

`z` ball is like the above "Subject"

when z . next,  ⇒ `takeUntil` will "Stop" the source Observable

As a result, the subscription method will "complete" when the `unsubscribe$` subject emits

and when the `unsubscribe$` subject emit? => When the component is going to destroy since `ngOnDestroy` will invoke before it's going to destroy

**Pro?**

1. The code inside `ngOnDestroy` is not going to touch again
2. when you subscribe, the declarative code make it explicit you made the unsubscription

**Con?**
I just think this logic is more complicated to understand. It required some knowledge to read code.

Actually, there's more ways to unsubscribe, and the reason I only introduce these two is because that the first one is the more simple-to-get one, and the second one the the one I had been seeing a lot in my working code base 😂

---

Let me know if you have questions. If you think I am not elaborate enough, feel free to see below links that I gathered for you :)

1. [Why It’s Important to Unsubscribe from RxJS Subscription | by Netanel Basal | Netanel Basal](https://www.notion.so/Why-It-s-Important-to-Unsubscribe-from-RxJS-Subscription-by-Netanel-Basal-Netanel-Basal-948ac83ee9124ab8811f88c6a951573c)
2. [When to Unsubscribe in Angular. As you probably know when you subscribe… | by Netanel Basal | Netanel Basal](https://www.notion.so/When-to-Unsubscribe-in-Angular-As-you-probably-know-when-you-subscribe-by-Netanel-Basal-Netane-30317e13657140c38c44ffff13902d97)
3. [RxJS - takeUntil](https://rxjs.dev/api/operators/takeUnti)
4. [The Best Way To Unsubscribe RxJS Observables In The Angular Applications! | by Tomas Trajan | Angular In Depth | Medium](https://medium.com/angular-in-depth/the-best-way-to-unsubscribe-rxjs-observable-in-the-angular-applications-d8f9aa42f6a0)
5. [takeUntil - Learn RxJS](https://www.learnrxjs.io/learn-rxjs/operators/filtering/takeuntil)
- [Using the takeUntil RxJS Operator to Manage Subscriptions Declaratively | DigitalOcean](https://www.digitalocean.com/community/tutorials/angular-takeuntil-rxjs-unsubscribe)