I am a part of an enterprise application in Angular 11. We use the NgRx store heavily and I was wondering if we can improve our application memory footprint by optimizing the subscriptions (currently the memory footprint is around ~200-220 MB and live JS Heap size ~76-85 MB).
To us, performance optimization is really important, as our clients don't refresh or close the browser window throughout the day and since we have enough subscriptions to serve our clients I need help to keep the memory footprint below the accepted limits and to not impact our clients.
We use subscriptions in the following manner:
private destroyed$: ReplaySubject <boolean> = new ReplaySubject(1);
ngOnInit(): void {
this.accountProgress$ = this.store.pipe(select(appState => appState.account.accountProgress), takeUntil(this.destroyed$));
...
...
this.accountProgress$.subscribe(() => {...})
}
ngOnDestroy(): void {
this.destroyed$.next(true);
this.destroyed$.complete();
}
Likewise, we have many other observable subscriptions that listen to different parts of App State. I have few queries:
- Can the subscription
this.accountProgress$.subscribe(() => {...})
still cause a memory leak? If it is used multiple times within the same component to fetch data in different methods? Should we usetakeUntil()
ortake(1)
with this kind of subscriptions as well (we have this at few places but I am not sure if it helps)? Or make use of share operators such aspublish() + refCount()
orshare({refCount: true})
withthis.store.pipe(select(appState => appState.account.accountProgress))
? - Sometimes we need to
dispatch
an action based on the value we receive within the subscription, I know that this is an anti-pattern that we should notdispatch
an action within a subscription, but what can be done, as few stores depend on API response and that is quite uncertain when it will return the data which will decide the further execution of the business logic - Are there any other ways to optimize? (Please note that we follow the aforementioned syntax of
takeUntil()
everywhere in our components wherever required, are there any other ways to prevent the memory consumption when dealing with NgRx store, Effects and Observables)