combineReducers
Reducer<
Combines multiple reducers into a single reducer function.
This is different from Redux's combineReducers in that it's fully typed and uses a record-based state structure for better type safety.
Example:
typedef AppState = ({int counter, List<String> todos});
final reducer = combineReducers<AppState>(
initialState: (counter: 0, todos: []),
slices: [
(
selector: (s) => s.counter,
updater: (s, v) => (counter: v, todos: s.todos),
reducer: counterReducer,
initialState: 0,
),
(
selector: (s) => s.todos,
updater: (s, v) => (counter: s.counter, todos: v),
reducer: todosReducer,
initialState: <String>[],
),
],
);
Implementation
Reducer<S> combineReducers<S>({
required S initialState,
required List<SliceDefinition<S, dynamic>> slices,
}) => (state, action) {
var hasChanged = false;
var nextState = state;
for (final slice in slices) {
final previousSliceState = slice.selector(nextState);
final nextSliceState = slice.reducer(previousSliceState, action);
if (!identical(previousSliceState, nextSliceState)) {
hasChanged = true;
nextState = slice.updater(nextState, nextSliceState);
}
}
return hasChanged ? nextState : state;
};