Single step debugging and source code analysis of ngrx store createselector

Time:2021-10-20

Source code:

import { Component } from '@angular/core';
import { createSelector } from '@ngrx/store';
 
export interface State {
  counter1: number;
  counter2: number;
}
 
export const selectCounter1 = (state: State) => state.counter1;
export const selectCounter2 = (state: State) => state.counter2;
export const selectTotal = createSelector(
  selectCounter1,
  selectCounter2,
  (counter1, counter2) => counter1 + counter2
); // selectTotal has a memoized value of null, because it has not yet been invoked.

Createselector internal:

Single step debugging and source code analysis of ngrx store createselector

function createSelector(...input) {
    return createSelectorFactory(defaultMemoize)(...input);
}

Defaultmemoize returns an object, and each field points to a function:

Single step debugging and source code analysis of ngrx store createselector

Single step debugging and source code analysis of ngrx store createselector

Input parameters I passed in three pure functions, that is, functions that can be executed repeatedly without side effect. These three pure functions are maintained in an array:

Single step debugging and source code analysis of ngrx store createselector

Enter the function body returned by createselectorfactory:

Single step debugging and source code analysis of ngrx store createselector

As can be seen from the source code, the last variable number of parameters received by createselector is treated as a projector, and the rest are treated as selectors

Single step debugging and source code analysis of ngrx store createselector

The discussion is divided into the following situations:

(1) For the first execution, lastarguments undefined, enter the if branch, execute projection, save the results, and return.
(2) If the execution is repeated and the input parameters do not change, the result of the previous execution will be returned directly
(3) If the execution is repeated and the parameters change, the project will be executed again
(4) If the result of the second execution is the same as that of the previous execution, the previous result is returned

Single step debugging and source code analysis of ngrx store createselector

The final returned by createselector is the selector with memory function:
Single step debugging and source code analysis of ngrx store createselector

If you want to debug later, remember that the approximate location of the code is 970 and search for the keyword memoized

More Jerry’s original articles are: “Wang Zixi”:
Single step debugging and source code analysis of ngrx store createselector