when<SubState> method

Reducer<State, Action, Environment> when<SubState>(
  1. Reducer<SubState, Action, Environment> subReducer
)

Conditionally applies subReducer when the current state is of type SubState.

This enables type-based state discrimination, useful when your state is a sealed class hierarchy. The sub-reducer only runs when the state matches the expected type.

Implementation

Reducer<State, Action, Environment> when<SubState>(
  Reducer<SubState, Action, Environment> subReducer,
) {
  return ifLet<SubState, Action, Environment>(
    stateLens: (
      get: (state) => state is SubState ? state as SubState : null,
      set: (state, localState) {
        if (localState is State) {
          return localState;
        } else {
          return state;
        }
      },
    ),
    actionLens: (
      embed: (localAction) => localAction,
      extract: (action) => action,
    ),
    toLocalEnvironment: (p0) => p0,
    child: subReducer,
  );
}