Store<State extends Built<State, StateBuilder> , StateBuilder extends Builder<State, StateBuilder> , Actions extends ReduxActions> constructor
Store<State extends Built<State, StateBuilder> , StateBuilder extends Builder<State, StateBuilder> , Actions extends ReduxActions> (
- Reducer<
State, StateBuilder, dynamic> reducer, - State defaultState,
- Actions actions, {
- Iterable<
Middleware< middleware = const [],State, StateBuilder, Actions> >
Implementation
Store(
Reducer<State, StateBuilder, dynamic> reducer,
State defaultState,
Actions actions, {
Iterable<Middleware<State, StateBuilder, Actions>> middleware = const [],
}) {
// set the initial state
_state = defaultState;
_actions = actions;
final api = MiddlewareApi<State, StateBuilder, Actions>(this);
// setup the dispatch chain
ActionHandler handler = (action) {
var state = _state.rebuild((b) => reducer(_state, action, b));
// if the state did not change do not publish an event
if (_state == state) return;
// update the internal state and publish the change
if (!_stateController.isClosed)
_stateController.add(
StoreChange<State, StateBuilder, dynamic>(state, _state, action));
_state = state;
};
// if middleware is give build the chain
if (middleware.isNotEmpty) {
// Scope each function with the store's api
Iterable<NextActionHandler> chain = middleware.map((m) => m(api));
// combine each middeware
NextActionHandler combinedMiddleware = chain.reduce(
(composed, middleware) => (handler) => composed(middleware(handler)));
// make the last middleware in the chain call the top-level reducer
handler = combinedMiddleware(handler);
}
// call the handler when an action is dispatched
actions.setDispatcher(handler);
}