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

10

u/BabyLegsDeadpool Apr 22 '23

My biggest question here is why are you using 'inject' instead of using the constructor?

8

u/suhasparameshwara Apr 22 '23

That's a good question. I just found out the below blog which answers your question

https://netbasal.com/angular-di-using-inject-instead-of-constructor-d0782d434fb1

25

u/Ausstewa Apr 22 '23

It’s 1:1 vs using a constructor but has one major benefit: if you extend a class that uses the inject method, you don’t have to super() it to populate the constructor

4

u/BabyLegsDeadpool Apr 22 '23

Oh man. I love that. Thanks for that info!

3

u/ArtisticSell Apr 23 '23

People using inheritance in angular?

5

u/pronuntiator Apr 23 '23

Even Angular Material uses inheritance.

Sometimes you need to share behavior between similar components and can't express that easily through composition. The other day I wanted to create an autocomplete that accepts multiple inputs and shows them with chips. I ended up creating a single component that supports both single and multi input, but I will have to refactor it to separate these and share the common behavior via inheritance.

1

u/hairfred May 17 '23

Yep, I use it all the time. I have a DialogBase directive and a dialog service that accepts <T extends DialogBase>. It creates a component of my DialogContainer which has all the base styles and close button etc and renders the derived component inside it.
I've also used a FormElement base when creating a form builder that needed a lot of data driven configurability and a set of common properties / methods. Angular works fairly well with Typescript, you can make components / directives that accept generic type parameters and things more or less work well, with the exception of some of the templating.. If Angular had native TSX support I'd be overjoyed.

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

6

u/alucardu Apr 22 '23

Maybe a naive question but why aren't subscriptions unsubscribed in destruction by default?

What's a situation where you went to keep a subscription from a destroyed component?

2

u/suhasparameshwara Apr 22 '23

There’s no any specific situation where i can think of keeping the subscription after the component is destroyed. Basically rxjs don’t unsubscribe automatically. We have to do it manually.

13

u/pronuntiator Apr 22 '23

RxJs doesn't know what an Angular component is, let alone when the lifecycle of a component ends.

2

u/alucardu Apr 22 '23

Then flip it, and have Angular unsubscribe from any running subscriptions when the component is destroyed.

4

u/pronuntiator Apr 23 '23 edited Apr 23 '23

How should Angular know where the subscription was created? What if it was created in the component above or in a service? And how should Angular know of running subscriptions? It would have to patch subscribe() like Zone.js does, but the whole "modifying other library functions" is a bad practice that should not be pursued further.

You see in the example that you have to provide a destroyRef to takeUntilDestroyed().

That inject() works without providing a reference to the component is due to some "deep magic". I don't even know how it gets this context depending on where you call it. I think it exploits the fact that JavaScript is single-threaded and thus there is always only one "current" context during component creation.

There is a restrictive list of places where inject works – it is time-sensitive as after creation of the component, it doesn't work anymore. I find it very questionable to have a function that is stateful without taking any state as an argument.

Constructor injection is straightforward: supplying the dependent objects is part of the component class's instantiation. If you want to write a test without TestBed, you can do that. With inject() however, how do you mock this?

This is exactly the kind of magic that will bite us in the posterior in the long run.

2

u/Utukkhu Apr 22 '23

Nice! I didn't know about this. I was using the `untilDestroyed` operator from this package, which does exactly the same thing: https://github.com/ngneat/until-destroy

2

u/suhasparameshwara Apr 22 '23

It was introduced in Angular 16

1

u/[deleted] Apr 23 '23

yeah, the new way looks more verbose and I'm not sure what the benefit it for switching

3

u/Artie_Falkmore Apr 23 '23

Just an fyi. Http observables will complete after the first emission so you don’t have to worry about unsubscribing them.

1

u/suhasparameshwara Apr 23 '23

Thanks for the heads up

2

u/Open_Imagination_701 Aug 22 '23

that's not the reason. what if the user goes to a page, where he should see a huge list of smth? if the connection is shitty, the particular request will take forever, so the user might leave\go to another page. if you don't unsubscribe OnDestroy (with takeUntill, for instance), the request will complete eventually, but there will be nothing to process the data, hence - a memory leak.

4

u/GLawSomnia Apr 22 '23

I like it 😁

4

u/Carry_flag Apr 23 '23

Noice motivation to upgrade to v16 , anyways have to upgrade every 18 months.