**Observables **are construct to which you subscribe to be informed about changes in data. They are stream of data ,whenever a new data piece is emitted our subscription will know it.
In Angular, we already have observables,you only subscribe them.You don’t have to create them.
Observables are added by a package name RxJS.
Interval is a built in function that gives observables.
It will give us observers like:
Now let’s say we have made this observable on home component and we have moved to another component now called profile component .
If you check dev tools ,you can still notice count incrementing even though we declared it in the home component it is still persisting in our profile component.
**So if we navigate away from component that doesn’t stop observables.
This may cause some serious problems like you may run out of resource ,it will slow your app and worst memory leakage may happens**
How you can Unsubscribe your observable?
1.declare your private subscription
2.You have to import Subscription from ‘rxjs’.
3.Now we store subscription returned by subscribe in our variable.
4.Now you can implement ngOnDestroy() hook of angular to destroy observable.
Now whenever we leave the component, we clear the subscription by unsubscribing and prevent memory leaks.
Important point to note here:All the Angular Package Observable like http,params that are built in angular Observable,You don’t have to worry about unsubscribing ,Angular handles that automatically.Therefore in most cases of Angular observables we don’t unsubscribe.
Thanks for reading, If you like it please share and comment
Top comments (0)