Skip to content

feat(store) use store.select with multiple selectors #3232

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion modules/store/spec/store.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,20 +29,22 @@ interface TestAppSchema {
counter2: number;
counter3: number;
counter4?: number;
actionCount: number;
}

describe('ngRx Store', () => {
let store: Store<TestAppSchema>;
let dispatcher: ActionsSubject;

function setup(
initialState: any = { counter1: 0, counter2: 1 },
initialState: any = { counter1: 0, counter2: 1, actionCount: 0 },
metaReducers: any = []
) {
const reducers = {
counter1: counterReducer,
counter2: counterReducer,
counter3: counterReducer,
actionCount: (state: number | undefined) => (state ?? 0) + 1,
};

TestBed.configureTestingModule({
Expand Down Expand Up @@ -222,6 +224,42 @@ describe('ngRx Store', () => {
);
});

it('should let you select state with multiple selector functions and only return distinct results', () => {
const actionSequence = '--a--b--c--d--e--f';
const actionValues = {
a: { type: INCREMENT },
b: { type: INCREMENT },
c: { type: DECREMENT },
d: { type: RESET },
e: { type: INCREMENT },
f: { type: 'OTHER' }, // state will change because actionCount will increment
};

const counterSteps = hot(actionSequence, actionValues);

counterSteps.subscribe((action) => store.dispatch(action));

const counterStateWithFunc = store.select(
(s) => s.counter1,
(s) => s.counter2,
(s) => s.counter3
);

const stateSequence = 'i-v--w--x--y--z---';
const counter1Values = {
i: [0, 1, 0],
v: [1, 2, 1],
w: [2, 3, 2],
x: [1, 2, 1],
y: [0, 0, 0],
z: [1, 1, 1],
};

expect(counterStateWithFunc).toBeObservable(
hot(stateSequence, counter1Values)
);
});

it('should correctly lift itself', () => {
const result = store.pipe(select('counter1'));

Expand Down
57 changes: 50 additions & 7 deletions modules/store/src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ export class Store<T = object>
}

select<K>(mapFn: (state: T) => K): Observable<K>;
select<Results extends unknown[]>(
...mapFns: [...{ [i in keyof Results]: (state: T) => Results[i] }]
): Observable<Results>;
/**
* @deprecated Selectors with props are deprecated, for more info see {@link https://github.com/ngrx/platform/issues/2980 Github Issue}
*/
Expand Down Expand Up @@ -137,6 +140,9 @@ export class Store<T = object>

export const STORE_PROVIDERS: Provider[] = [Store];

export function select<T, Results extends unknown[]>(
...mapFns: [...{ [i in keyof Results]: (state: T) => Results[i] }]
): (source$: Observable<T>) => Observable<Results>;
export function select<T, K>(
mapFn: (state: T) => K
): (source$: Observable<T>) => Observable<K>;
Expand Down Expand Up @@ -225,19 +231,35 @@ export function select<
...paths: string[]
): (source$: Observable<T>) => Observable<K>;
export function select<T, Props, K>(
pathOrMapFn: ((state: T, props?: Props) => any) | string,
propsOrPath?: Props | string,
...paths: string[]
...[pathOrMapFn, propsOrPathOrMapFn, ...pathsOrMapFns]:
| string[]
| [(state: T, props?: Props) => any, Props | string, ...string[]]
| ((state: T) => any)[]
) {
return function selectOperator(source$: Observable<T>): Observable<K> {
let mapped$: Observable<any>;

if (typeof pathOrMapFn === 'string') {
const pathSlices = [<string>propsOrPath, ...paths].filter(Boolean);
mapped$ = source$.pipe(pluck(pathOrMapFn, ...pathSlices));
const pathSlices = [<string>propsOrPathOrMapFn, ...pathsOrMapFns].filter(
Boolean
);
mapped$ = source$.pipe(pluck(pathOrMapFn, ...(pathSlices as string[])));
} else if (typeof propsOrPathOrMapFn === 'function') {
mapped$ = source$.pipe(
map(
(source: T) =>
new SelectedValues([
pathOrMapFn(source),
(propsOrPathOrMapFn as (state: T, props?: Props) => any)(source),
...(
(pathsOrMapFns ?? []) as ((state: T, props?: Props) => any)[]
).map((fn) => fn(source)),
])
)
);
} else if (typeof pathOrMapFn === 'function') {
mapped$ = source$.pipe(
map((source) => pathOrMapFn(source, <Props>propsOrPath))
map((source) => pathOrMapFn(source, <Props>propsOrPathOrMapFn))
);
} else {
throw new TypeError(
Expand All @@ -246,6 +268,27 @@ export function select<T, Props, K>(
);
}

return mapped$.pipe(distinctUntilChanged());
return mapped$.pipe(
distinctUntilChanged((previous, current) => {
if (
current instanceof SelectedValues &&
previous instanceof SelectedValues
Comment on lines +274 to +275
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I needed to use a distinct class to hold multiple selected values so that they could be distinguished from a single selected array value.

) {
return (
current.values.length === previous.values.length &&
current.values.every(
(currentValue: unknown, i: number) =>
currentValue === previous.values[i]
)
);
}
return previous === current;
}),
map((v) => (v instanceof SelectedValues ? v.values : v))
);
};
}

class SelectedValues<T extends unknown[]> {
constructor(public readonly values: T) {}
}