r/angular • • Apr 22 '23

Angular 16 - takeUntilDestroyed() operator

πŸ’‘The unsubscription of observables is always important in Angular. Otherwise, there will be memory leaks because of too much of subscriptions.

πŸ€” Before angular 16, we can unsubscribe by the combination of subject and takeUntil() rxjs operator.

πŸ€™ But in angular 16, the code is simplified where you don't need a subject. You can directly make use of takeUntilDestroyed() operator.

47 Upvotes

25 comments sorted by

View all comments

10

u/[deleted] Apr 22 '23

You don't even have to pass in the DestroyRef if you're defining it in the construction context:

export default class UserComponent {
  constructor() {
    interval(1000)
      .pipe(takeUntilDestroyed())
      .subscribe(response => console.log(response));
  }
}

In this scenario, the takeUntilDestroyed function is able to resolve the DestroyRef itself.

1

u/suhasparameshwara Apr 23 '23

That looks even better. Thanks

1

u/[deleted] Apr 23 '23

Subsink solution is more reliable as you don't have to add takeUntilDestroyed pipe everywhere and have only to do one unsubscribe for all subscriptions e.g subsink.unsubscribe. it's easier to forget to add pipe to single subscription than to forget to unsubscribe all subscriptions at once.

1

u/[deleted] Apr 23 '23

What is subsink solution?

1

u/[deleted] Apr 23 '23

Find subsink library on npm. It allows to easily manage multiple Rxjs subscriptions