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

前端 未结 9 1792
醉酒成梦
醉酒成梦 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.

提交回复
热议问题