Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 observables declared with takeUntilDestroyed, when combined, require additional takeUntilDestroyed?

I'm using takeUntilDestroyed to manage my subscriptions and avoid memory leaks. Within an injection context, variable declaration, I will have something like this

mySubject1$ = new BehaviourSubject<void>(void 0);
myData1$ = mySubject1$.pipe(takeUntilDestroyed(), switchMap(() => myService.getData1()));
mySubject2$ = new BehaviourSubject<void>(void 0);
myData2$ = mySubject2$.pipe(takeUntilDestroyed(), switchMap(() => myService.getData2()));

In my constructor I want to combine these, do I need to use takeUntilDestroyed() again?

constructor(){
combineLatest([myData1$, myData2$]).pipe(takeUntilDestroyed())...
}
like image 749
Fred2020 Avatar asked Dec 07 '25 08:12

Fred2020


1 Answers

You don't need takeUntilDestroyed on the service, you need to add it on the subscription of the component (my point being the components are destroyed often, not services).

But it looks like, the combineLatest will be unsubscribed, when the service is destroyed, but if you have providedIn: 'root' on the service, it's never destroyed.

So, keep the take until destroyed on the component level, to prevent problems.

mySubject1$ = new BehaviourSubject<void>(void 0);
myData1$ = mySubject1$.pipe(switchMap(() => myService.getData1()));
mySubject2$ = new BehaviourSubject<void>(void 0);
myData2$ = mySubject2$.pipe(switchMap(() => myService.getData2()));

In the component

constructor(){
    combineLatest([myData1$, myData2$]).pipe(takeUntilDestroyed())...
}
like image 174
Naren Murali Avatar answered Dec 11 '25 11:12

Naren Murali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!