Does overriding a Subscription automatically unsubscribes the previous value?

Viewed 195

I have the following subscription in an angular application:

  private _sub: Subscription;

On initialization I subscribe to a firebase get function:

this._sub = this.service.get('database1').subscribe(
   data => {
      this.ListOfData = data;
   }
);

But depending on user input I change database1 to other collections, or use a different method instead of get().

When I override _sub will the previous stream get automatically unsubcribed, or do I have to manually do it before overriding?

2 Answers

Short answer: No it doesn't...I'll share the details on why

Whenever .subscribe() is called, a new instance of a Subscription is created that holds resources that listen to the execution of the Observable. If you call .subscribe() and do not call .unsubscribe(), your Subscription is still utilizing resources. In some cases (depending on the logic associated to the Observable/Subject) it can result in unexpected behavior in your application and it can impact performance. This is why the best practice is to call .unsubscribe() on your Subscription when you are done with it.

There are also functions called RxJS operators that can help you to manage your subscriptions by automatically unsubscribing based on certain criteria.

No, you have to unsubscribe. Sometimes they stay like sleeper cells to damage your application performance. Best practice is unsubscribe.

Related