Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to unsubscribe from a Redux store in an Angular component

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.

like image 662
ktsangop Avatar asked Jun 02 '17 06:06

ktsangop


People also ask

Is unsubscribe is necessary Angular?

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.

What happens if I don't unsubscribe Angular?

Specifically, we must unsubscribe before Angular destroys the component. Failure to do so could create a memory leak.

Do you need to unsubscribe from NgRx store?

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.

Do I need to unsubscribe from router events?

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.


1 Answers

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().

like image 153
Amit Chigadani Avatar answered Nov 15 '22 03:11

Amit Chigadani