5. Reducer

James Shvarts edited this page Dec 11, 2018 · 1 revision

Reducer is responsible for creating a new State based on a previous State plus latest Change. It is the only way to produce new immutable States which essentially makes it the single source of truth for our State Machine.

In Roxie, Reducer is a one-liner implementing a typealias as follows:

typealias Reducer<S, C> = (state: S, change: C) -> S  

where S is a previous State and C is a Change.

Each ViewModel defines its own Reducer applicable within its context. For instance, on a screen listing notes, your Reducer may look as follows:

    private val reducer: Reducer<State, Change> = { state, change ->
        when (change) {
            is Change.Loading -> state.copy(
                isIdle = false,
                isLoading = true,
                notes = emptyList(),
                isError = false
            is Change.Notes -> state.copy(
                isLoading = false,
                notes = change.notes
            is Change.Error -> state.copy(
                isLoading = false,
                isError = true

Here we use Kotlin data class copy() operator to create a new State based on the last State while overwriting only those properties that changed based on the Change handled.

Reducer is a pure function (it has no side effects). If you were to look at an existing code that you are not familiar with, the Reducer would be a great place to start. It gives you a great overview of the functionality for a given feature/screen.

We execute the Reducer by using RxJava operator scan() as follows:

    .scan(initialState, reducer)

For details on the scan() operator, check out the official docs

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.