Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to subscription if you don't assign it to a variable?

Tags:

angular

I'm trying to figure out why all of the Angular apps I look at assign subscriptions to a variable, only to have to unsubscribe via ngOnDestroy(). For example:

export class ViewBookPageComponent implements OnDestroy {
  actionsSubscription: Subscription;

  constructor(store: Store<fromRoot.State>, route: ActivatedRoute) {
    this.actionsSubscription = route.params
      .select<string>('id')
      .map(id => new book.SelectAction(id))
      .subscribe(store);
  }

  ngOnDestroy() {
    this.actionsSubscription.unsubscribe();
  }
}

What happens if I just remove actionsSubscription altogether? Will a subscription still be created but not destroyed? In the below case, you still get the side-effect, but don't have to bother unsubscribing. So is actionsSubscription necessary for garbage collection?

export class ViewBookPageComponent {

  constructor(store: Store<fromRoot.State>, route: ActivatedRoute) {
    route.params
      .select<string>('id')
      .map(id => new book.SelectAction(id))
      .subscribe(store);
  }

}
like image 678
T. Ato Avatar asked Sep 03 '25 15:09

T. Ato


1 Answers

You are right, if you remove actionsSubscription altogether, the subscription will still be created but you won't be able to unsubscribe from it via ngOnDestroy, after you leave the component. If not unsubscribed, the observable might still keep streaming data, even after moving away from the component, hence causing memory leaks. So, assigning an observable subscription to a variable and forcing unsubscribe ensures that the data stream from that observable is stopped when component is destroyed.

I learned more about unsubscribe from this article by Brian Love.

One important thing I noted from it -

if you are using observable streams via the AsyncPipe then you do not need to worry about unsubscribing. The async pipe will take care of subscribing and unsubscribing for you.

Hope this helps.

like image 171
Nehal Avatar answered Sep 05 '25 04:09

Nehal