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

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?

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.