wrapReduce method

Reducer<St> wrapReduce(
  1. Reducer<St> reduce,
  2. Store<St> store
)

Implementation

Reducer<St> wrapReduce(
  Reducer<St> reduce,
  Store<St> store,
) {
  //
  if (!ifShouldProcess())
    return reduce;
  //
  // 1) Sync reducer.
  else {
    if (reduce is St? Function()) {
      return () {
        //
        // The is the state right before calling the sync reducer.
        St oldState = store.state;

        // This is the state returned by the reducer.
        St? newState = reduce();

        // If the reducer returned null, or returned the same instance, don't do anything.
        if (newState == null || identical(store.state, newState)) return newState;

        return process(oldState: oldState, newState: newState);
      };
    }
    //
    // 2) Async reducer.
    else if (reduce is Future<St?> Function()) {
      return () async {
        //
        // The is the state returned by the reducer.
        St? newState = await reduce();

        // This is the state right after the reducer returns,
        // but before it's committed to the store.
        St oldState = store.state;

        // If the reducer returned null, or returned the same instance, don't do anything.
        if (newState == null || identical(store.state, newState)) return newState;

        return process(oldState: oldState, newState: newState);
      };
    }
    // Not defined.
    else {
      throw StoreException("Reducer should return `St?` or `Future<St?>`. "
          "Do not return `FutureOr<St?>`. "
          "Reduce is of type: '${reduce.runtimeType}'.");
    }
  }
}