I am almost certain that i should, but i have not found any specific information on the Redux documentation. My pattern in most of my Angular components, is that i subscribe/unsubscribe to a Redux store like :
import { Component, OnInit } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'selector',
templateUrl: 'name.component.html'
})
export class ComponentNameComponent implements OnInit {
private unsubscribe : Function;
constructor(@Inject(AppStore) private store: Store<AppState>) {}
ngOnInit() {
this.unsubscribe = this.store.subscribe ( ()=>{ this.updateFromState(); });
}
// Is unsubscribing onDestroy necessary?
ngOnDestroy(){
this.unsubscribe();
}
this.updateFromState(){
// ...
}
}
So i would like to know if i should always unsubscribe from the Store, and what would happen if i didn't.
In Angular applications, it's always recommended to unsubscribe the observables to gain benefits like: Avoids Memory Leaks. Aborting HTTP requests to avoid unwanted calls.
Specifically, we must unsubscribe before Angular destroys the component. Failure to do so could create a memory leak.
Effects are the primary way of handling logic within NgRx. They allow us to observe streams of actions and react to them. We do not need to subscribe to any effect nor do you need to manually unsubscribe.
Generally you do not need to unsubscribe from HTTP calls. The ActivatedRoute and its observables are insulated from the Router itself so the Angular Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.
Yes you should destroy (unsubscribe)
all the observables within your application when they are not in use. I have no idea about Redux store
, but I feel you should still kill your observables in onDestroy
.
What happens if you don't unsubscribe()?
First time when your component is loaded ngOnInit()
will subscribe to store
and now again if you go back to some other component and then revisit the same component, you will have new subscription
along with previous one (so 2 subscriptions). This subscription
count increases as many times as you revisit the component, which will reduce the performance of your application. So safer side you should be killing the previous subscription
before creating new one, which is usually done in ngOnDestroy()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With