Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngrx/store subscribe being called multiple times. Best place to unsubscribe?

I have an angular component that contains a NgModal popup.

I am subscribing to the ngrx store in the component.

The component's ngOnDestroy is never called because a new route is never called.

The user add's new Users via the modal popup.

The subscription(select) to the store for the 'user' state never unsubscribes and is being called many times.

What is the best way to handle the unsubscribing from a store.select() when ngOnDestroy() is never called?

like image 716
Michael JDI Avatar asked Oct 24 '25 09:10

Michael JDI


2 Answers

The easiest way around this issue is don't subscribe in your component, do it in the template through the async pipe.

From the Angular Docs:

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks (emphasis added).

Since you mentioned ngOnDestroy is not called, then most likely the component persists and is hidden/shown as needed, in which case you'll just get the single subscribe.

You can also prevent multiple subscribe calls in the template by using the "async as" pattern, as explained by Todd Motto here.. Basically, when encountering the need for multiple async pipes in a template, use *ngIf="data$ | async as data" at a higher element and reference the resolved data below.

like image 99
John Neuhaus Avatar answered Oct 27 '25 03:10

John Neuhaus


Destroying the Subscription inside ngOnDestroy() is useful, if you don't want that subscription to be called in different components

However, if the subscription is getting called multiple time within the same component you can solve this by using RxJs Operators

yourSelectorname$.pipe(skip(1)).pipe(take(1)).subscribe

or

yourSelectorname$.pipe(take(1)).subscribe

It depends according to your need

like image 36
Manas Avatar answered Oct 27 '25 02:10

Manas