rxjsngrxngrx-storerxjs-pipeable-operatorsngrx-entity

NgRx store select Vs map behaviors


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?


Solution

  • Selectors are memoized, which means that they're only invoked when the input changes. The select method also uses the distinctUntilChanged() operator under the hood.

    By just using map the subscribe block will be invoked everytime the state changes.