8

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!

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
David
  • 3,364
  • 10
  • 41
  • 84
  • Be aware of your cold/hot Observables (https://medium.com/@benlesh/hot-vs-cold-observables-f8094ed53339). A hot one can fire multiple times e.g. a Subject that you call .next() on. Other ones like the http call give you a cold Observable which completes (or fails) just once. – Ore Jan 30 '18 at 08:15

1 Answers1

24

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'));
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112