Why do you need to unsubscribe of observables in OnDestroy hook?
- Observable can emit multiple values, so if you want to stop evaluating logic after destroying (closing) component you would need to call unsubscribe
- If component is closed and request is still pending the unneeded logic could evaluate after component is closed
And sometimes it is tempting to write something like this:
/* don't do this */
this.sub = this.source$.subscribe((response) => {
/* some logic */
this.sub.unsubscribe();
});
this will unsubscribe after first got value, but it will not unsubscribe if request is too long to complete. So this is not the best way of unsubscribe. There are many other convenient technics to unsubscribe.
Cheers
Leave a Reply