When should I store the Subscription
instances and invoke unsubscribe()
during the NgOnDestroy life cycle and when can I simply ignore them?
It depends. If by calling someObservable.subscribe()
, you start holding up some resource that must be manually freed-up when the lifecycle of your component is over, then you should call theSubscription.unsubscribe()
to prevent memory leak.
Let's take a closer look at your examples:
getHero()
returns the result of http.get()
. If you look into the angular 2 source code, http.get()
creates two event listeners:
_xhr.addEventListener('load', onLoad);
_xhr.addEventListener('error', onError);
and by calling unsubscribe()
, you can cancel the request as well as the listeners:
_xhr.removeEventListener('load', onLoad);
_xhr.removeEventListener('error', onError);
_xhr.abort();
Note that _xhr
is platform specific but I think it's safe to assume that it is an XMLHttpRequest()
in your case.
Normally, this is enough evidence to warrant a manual unsubscribe()
call. But according this WHATWG spec, the XMLHttpRequest()
is subject to garbage collection once it is "done", even if there are event listeners attached to it. So I guess that's why angular 2 official guide omits unsubscribe()
and lets GC clean up the listeners.
As for your second example, it depends on the implementation of params
. As of today, the angular official guide no longer shows unsubscribing from params
. I looked into src again and found that params
is a just a BehaviorSubject. Since no event listeners or timers were used, and no global variables were created, it should be safe to omit unsubscribe()
.
The bottom line to your question is that always call unsubscribe()
as a guard against memory leak, unless you are certain that the execution of the observable doesn't create global variables, add event listeners, set timers, or do anything else that results in memory leaks.
When in doubt, look into the implementation of that observable. If the observable has written some clean up logic into its unsubscribe()
, which is usually the function that is returned by the constructor, then you have good reason to seriously consider calling unsubscribe()
.