Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we need to unsubscribe from http calls in Angular? [duplicate]

Probably a silly question, but couldn't find an answer easily.

In an Angular application where I'm using Rxjs to make http calls to get and post data to a server. Let's say I have a service MyService with a method like this:

getData() {
  this.http
      .get("mybackendurl/mydata")
      .map(res => res.json())
      .subscribe(data => this.data = data);
}

So, let's say I use this method in a couple places and a every time I navigate into a page. Regardless of the convenience of doing it this way, my question is, this is not like a Promise, that starts and finishes, as far as I know this keeps a connection open until the source terminates, so do I need to somehow unsubscribe from this every time I finish the request?

As the subscription is done in a service and not in a component, the service won't be destroyed, hence I fear I might be creating multiple subscriptions and connections instead of reusing the same one.

Thanks!

like image 363
David Avatar asked Jan 30 '18 07:01

David


1 Answers

For Http request you don't need to unsubscribe. It actually completes the observable, so you will not have any memory leaks.

You can check this by using add function of the Subscription object. This function is called when Subscription is unsubscribed. Also you can check via passing the complete function (the 3rd parameter) into the subscribe function, which will be called after the request and will mean that observable is completed.

this.http
    .get("mybackendurl/mydata")
    .map(res => res.json())
    .subscribe(data => this.data = data)
    .add(() => console.log('Unsubscribed'));
like image 128
Suren Srapyan Avatar answered Sep 23 '22 20:09

Suren Srapyan