I have a NgRx store EntityAdapter from where I can retrieve a list of customers with the following call:
this.store.pipe(select(this.selectCustomersFunction))
.subscribe(items => {
console.log('======> Select Customers Function Called'); // Executed only one time
});
The above code works, and I can see the code inside the subscribe is called only once.
I changed this to the following with the RxJS map function:
this.store.pipe(
map((state: CustomerState) => this.selectCustomersFunction(state))
)
.subscribe(items => {
console.log('======> Select Items Function Called'); // Executed numerous times
});
The code inside the subscribe gets called multiple times.
These are the EntityAdapter methods:
export const selectAllCustomers = createSelector(
fromPortal.getCustomerEntitiesState,
fromCustomer.selectAllCustomers
);
const {
selectIds,
selectEntities,
selectAll,
selectTotal,
} = adapter.getSelectors();
// select the array of customers
export const selectAllCustomers = selectAll;
Why does the code with map get called multiple times?
Selectors are memoized, which means that they're only invoked when the input changes. The
selectmethod also uses thedistinctUntilChanged()operator under the hood.By just using
mapthe subscribe block will be invoked everytime the state changes.