Is it necessary to unsubscribe from observables created by Http methods?

前端 未结 9 1675
醉酒成梦
醉酒成梦 2020-11-22 04:50

Do you need to unsubscribe from Angular 2 http calls to prevent memory leak?

 fetchFilm(index) {
        var sub = this._http.get(`http://example.com`)
              


        
相关标签:
9条回答
  • 2020-11-22 05:14

    So the answer is no, you don't. Ng2 will clean it up itself.

    The Http service source, from Angular's Http XHR backend source:

    Notice how it runs the complete() after getting the result. This means it actually unsubscribes on completion. So you don't need to do it yourself.

    Here is a test to validate:

      fetchFilms() {
        return (dispatch) => {
            dispatch(this.requestFilms());
    
            let observer = this._http.get(`${BASE_URL}`)
                .map(result => result.json())
                .map(json => {
                    dispatch(this.receiveFilms(json.results));
                    dispatch(this.receiveNumberOfFilms(json.count));
                    console.log("2 isUnsubscribed",observer.isUnsubscribed);
                    window.setTimeout(() => {
                      console.log("3 isUnsubscribed",observer.isUnsubscribed);
                    },10);
                })
                .subscribe();
            console.log("1 isUnsubscribed",observer.isUnsubscribed);
        };
    }
    

    As expected, you can see that it is always unsubscribed automatically after getting the result and finishing with the observable operators. This happens on a timeout (#3) so we can check the status of the observable when it's all done and completed.

    And the result

    So, no leak would exist as Ng2 auto unsubscribes!

    Nice to mention: This Observable is categorized as finite, on contrary to the infinite Observablewhich is an infinite stream of data can be emitted like DOM click listener for example.

    THANKS, @rubyboy for help on this.

    0 讨论(0)
  • 2020-11-22 05:18

    Calling the unsubscribe method is rather to cancel an in-progress HTTP request since this method calls the abort one on the underlying XHR object and remove listeners on the load and error events:

    // From the XHRConnection class
    return () => {
      _xhr.removeEventListener('load', onLoad);
      _xhr.removeEventListener('error', onError);
      _xhr.abort();
    };
    

    That said, unsubscribe removes listeners... So it could be a good idea but I don't think that it's necessary for a single request ;-)

    Hope it helps you, Thierry

    0 讨论(0)
  • 2020-11-22 05:20

    You should definitely read this article. It shows you why you should always unsubscribe even from http.

    If after creating the request but before receiving an answer from the back-end you deem the component unnecessary and destroy it, your subscription will maintain the reference to the component thus creating a chance for causing memory leaks.

    Update

    The above affirmation seems to be true, but anyway, when the answer comes back the http subscription is destroyed anyway

    0 讨论(0)
提交回复
热议问题