-
Notifications
You must be signed in to change notification settings - Fork 6
Reducer
Reducer is a function that takes the current state and an action and returns a new state. This new state would then be saved as the current state to be used on the next call to the reducer. In Kaskade, there's a reducer created for every action.
on<TodoAction.Update> {
todoRepository.updateItem(action.todoItem)
TodoState.OnUpdated(action.position, action.todoItem)
}
In the DSL example the reducer is abstracted as the lambda in the on
method. It has an ActionState
, which is a pair of action and state, receiver. ActionState is for the DSL to easily access both action and state.
The interface of a Reducer
is:
interface Reducer<ACTION : Action, STATE : State> {
operator fun invoke(action: ACTION, state: STATE, onStateChanged: (state: STATE) -> Unit)
}
The reducer
is being invoked every time an action is processed.
The default reducer is the BlockingReducer
which synchronously runs the lambda in the on
method of the DSL.
class BlockingReducer<ACTION : Action, STATE : State>(
private val transformerFunction: ActionState<ACTION, STATE>.() -> STATE
) : Reducer<ACTION, STATE> {
override fun invoke(action: ACTION, state: STATE, onStateChanged: (state: STATE) -> Unit) {
onStateChanged(getState(action, state))
}
fun getState(action: ACTION, state: STATE) = transformerFunction(ActionState(action, state))
}
It is not a good idea to run long running tasks on it. For asynchronous purposes there's a ScopedReducer and RxReducer in the Kaskade modules.