TIL, 2022-07-14, NGRX Unsubscribes
NGRX Common Gotcha’s
- Subscribing to a selector inside the component - needs to be unsubscribed if it isn’t in a pipe.
- Can do
takeUntil
ortake(1)
orUntilDestroy
.
ngOnInit() {
this.store.select(selectors.selectCustomer)
.subscribe((customer) = > {
this.customerIsCool = customer.supports === 'Southend'; <- Leak
});
});
- Feature selectors - Memoized selector and
createFeatureSelector
? - Flattening operators:
switchMap
cancels previous prior observables.mergeMap
andconcatMap
need to be used if you need to process the result of each API call. - Avoid unnecessary API calls:
@Effect() loadSomeData$ Observable;
constructor(private actions$: Actions, private store$: Store) {
this.loadSomeData$: Observable = this.actions$
.ofType(actions.LOAD_DATA)
.withLatestFrom(this.store$)
.switchMap(([action, state]) => {
const currentState = selectors.selectSomeState(state);
const loading = selectors.selectLoading(state);
if (currentState || loading) {
// We either already have the state in the store,
// or are already loading, so there is no need to
// kick off another API call
return empty();
}
return doApiCall()
.map((response: LoadDataResponse) => {
return new actions.Success(response);
})
.catch(() => of(new actions.Failed()));
});
- Ensure none of the state tree is mutated: NGRX store freeze Reference
When to Unsubscribe in Angular
valueChanges
.router
subscriptions.renderer
service.- Infinite sequence from
interval()
orfromEvent()
observables. - Select methods in NGRX.
- Don’t unsubscribe:
Async
pipe.@HostListener
.