title: Angular: Should I subscribe() to http.get() each time I need to update?
body: <p>I wonder if I am using Observable.subscribe() too many times or not.</p>
  
  <p>In my component class, I have a function loadData().
  It calls another function this.service.getData() that uses HttpClient.get() to perform a HTTP request to the server.</p>
  
  <p>Currently in my function loadData(), I subscribe to the result of this.service.getData().</p>
  
  <p>Each time the user clicks on a "Update" button, I would like to call my function loadData().</p>
  
  <h1>The question</h1>
  
  <ul>
  <li>If I call my function <strong>loadData()</strong> every time I need to perform HTTP request, will I create as many subscribers?</li>
  <li>Is there a risk of memory leaks?</li>
  <li>If so, do you know how I should refactor my code?</li>
  </ul>
  
  <h1>The answer</h1>
  
  <ul>
  <li>I found this other post <a href="https://stackoverflow.com/questions/35042929/is-it-necessary-to-unsubscribe-from-observables-created-by-http-methods">Is it necessary to unsubscribe from observables created by Http methods?</a></li>
  <li>It explains that the Angular code actually call observable.complete () after an HTTP request, with a delay</li>
  <li>So I modified my code below to check that fact and the tests confirmed that it was true</li>
  </ul>
  
  <h1>Samples of code</h1>
  
  <pre><code>private loadData() {
      this.loading = true;
       const subscription = this.service.getData()
        .pipe(
    // console.log() with a delay added for test - START
    map(val =&gt; {
      window.setTimeout(() =&gt; {
        // This will print true.
        console.log('After delay: Is Subscriber closed?', subscription.closed);
      }, 10);
      return val;
    }),
      // console.log() with a delay added for test - END
      takeUntil(this.ngUnsubscribe))
        .subscribe(data =&gt; {
          this.data = data;
          // This will print false.
          console.log('Is Subscriber closed?', subscription.closed);
        },
        error =&gt; {
          console.error(error);
          throw error;
        },
        () =&gt; {
          this.loading = false;
        });
  }
  getData(): Observable&lt;DataObject&gt; {
      const uri = encodeURI(this.configService.getUri());
      const headers = new HttpHeaders();
      if (this.pipelineEtag) {
        headers.set('If-None-Match', this.pipelineEtag);
      }
      return this.http.get(uri, {
        headers: headers,
        observe: 'response'
      }).pipe(
        map(resp =&gt; this.processResponse(resp)),
        catchError(error =&gt; this.handleError(error, this.envProduction))
      );
  }
  </code></pre>