Store<S> constructor

Store<S>({
  1. required S initialState,
  2. List<Bloc<S>> blocs = const [],
})

Implementation

Store({
  required S initialState,
  List<Bloc<S>> blocs = const [],
})  : states = BehaviorSubject<S>.seeded(initialState),
      _blocs = blocs {
  var dispatchStream = _dispatchController.stream.asBroadcastStream();
  var afterwareStream = _afterwareController.stream.asBroadcastStream();

  for (Bloc<S> bloc in blocs) {
    dispatchStream = bloc.applyMiddleware(dispatchStream);
    afterwareStream = bloc.applyAfterware(afterwareStream);
  }

  var reducerStream = dispatchStream.map<Accumulator<S>>(
      (context) => Accumulator(context.action, states.requireValue));

  for (Bloc<S> bloc in blocs) {
    reducerStream = bloc.applyReducer(reducerStream);
  }

  reducerStream.listen((a) {
    assert(a.state != null);
    states.add(a.state);
    _afterwareController.add(WareContext<S>(dispatch, a.state, a.action));
  });

  // Without something listening, the afterware won't be executed.
  afterwareStream.listen((_) {});
}