Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do i need to unsubscribe from an Ngrx Select

I have a component as follows, where I have a button calling select_property when clicked. The thing is im not sure whether i need to unsubscribe in any way before reassigning $livevisitors on each click , not sure whether $livevisitors | async in the component template does this work for me.

export class LiveComponent{

    livevisitors$: Observable<LiveVisitor[]>;
    selected_property_id: number = 0;

    constructor(
            private store: Store<AppState>
        ) {

        this.livevisitors$ = this.store.select(selectAllLiveVisitors);

    }

    select_property(id){
        this.selected_property_id = id;

        if (id == 0){
            this.livevisitors$ = this.store.select(selectAllLiveVisitors);
        } else {
            this.livevisitors$ = this.store.select(selectLiveVisitorsByPropertyId, {property_id: id});
        }
    }
like image 366
Yehia A.Salam Avatar asked Nov 07 '25 09:11

Yehia A.Salam


2 Answers

The async pipe subscribe and unsubscribe for you. You don't need to manage manual unsubscription.

From the official documentation :

When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

like image 61
Gérôme Grignon Avatar answered Nov 10 '25 09:11

Gérôme Grignon


However if you subscribe to the observable in your component, you introduce a potential memory leak:

export class LiveComponent{

    livevisitors$: Observable<LiveVisitor[]>;
    selected_property_id: number = 0;

    constructor(
            private store: Store<AppState>
        ) {

    }

     ngOnInit() {
        //Potential memory leak
        this.store.select(selectAllLiveVisitors).subscribe(() = > {...})

     }

}

if that is the case then you need to unsubscribe when the component is destroyed. An elegant solution to this is to declare a Subject property:

export class LiveComponent implements OnInit, OnDestroy {
    destroyed$: Subject<void> = new Subject<void>();
    livevisitors$: Observable<LiveVisitor[]>;
    selected_property_id: number = 0;

    constructor(
            private store: Store<AppState>
        ) {

    }

     ngOnInit() {
        // will unsubscribe when component is destroyed
        this.store.select(selectAllLiveVisitors)
           .pipe(takeUntil(this.destroyed$))
           .subscribe(() = > {...})

     }

     ngOnDestroy() {
        this.destroyed$.next();
        this.destroyed$.complete();
     }
}

like image 27
Or Shalmayev Avatar answered Nov 10 '25 08:11

Or Shalmayev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!