0

I know that when you create and connect a subscription in Angular you should always remember to unsubscribe in the OnDestroy to avoid memory leaks.

this.mySubscription = this.dataService.getAllUsers().subscribe();

ngOnDestroy(){
    if(this.mySubscription) this.mySubscription.unsubscribe();
}

However, I frequently see code where a service method is subscribed to and not assigned to a Subscription and so not expressly destroyed.

this.dataService.getAllUsers().subscribe(users => //do something with the users);

Is that bad practice, should you always assign every observable connection you make to a Subscription variable and expressly unsubscribe from it?

Also, if I do create a subscription variable and assign it as above, should I never reuse it within the same component?:

this.mySubscription = this.dataService.getAllUsers().subscribe();

// Later in the component

this.mySubscription = this.dataService.getUserDetail(user.Id).subscribe();

What, if any, are the pitfalls of this kind of reuse?

Full Time Skeleton
  • 1,680
  • 1
  • 22
  • 39
  • @AndrewAllen - yes, I did search before posting this but obviously used the wrong keywords. I suppose this question can be killed if necessary, thanks. – Full Time Skeleton May 13 '21 at 15:50
  • I have been using SubSink package for non self completing observables and have found it results in the cleanest way to manage subscriptions. When you get data using HttpClient it is self completing so you don’t need to assign it to a subscription to manually unsubscribe. – Ben L May 14 '21 at 00:00
  • @bjlasc01 thanks I'll investigate subsink. Anyone have any opinions on the reuse of a subscription within the component? – Full Time Skeleton May 14 '21 at 14:26

0 Answers0