Redux architecture revolves around a strict unidirectional data flow.
This means that all data in an application follows the same lifecycle pattern, making the logic of your app more predictable and easier to understand. It also encourages data normalization, so that you don't end up with multiple, independent copies of the same data that are unaware of one another.
If you're still not convinced, read Motivation and The Case for Flux for a compelling argument in favor of unidirectional data flow. Although Redux is not exactly Flux, it shares the same key benefits. There are also many talks on the benefits of UDF for Android & iOS development.
The data lifecycle in any Redux app follows these 4 steps:
- You call
An action is a plain object describing what happened. For example:
data class LikeArticle(val articleId: Int) data class FetchUserSuccess(val response: ApiResponse) data class AddTodo(val text: String)
Think of an action as a very brief snippet of news. “Mary liked article 42.” or “'Read the Redux docs.' was added to the list of todos.”
You can call
store.dispatch(action) from anywhere in your app or even at
//TODO note on threading & reducer -- also TODO note in reducer section on threading
- The Redux store calls the reducer function you gave it.
val previousState = AppState( visibilityFilter = VisibilityFilter.SHOW_ALL, todos = listOf( Todo( text = "Read the docs.", completed = false ) ) ) val action = AddTodo(text = "Understand the flow") // The action being performed (adding a todo) val nextState = todoReducer(previousState, action)
Note that a reducer is a pure function. It only computes the next state. It should be completely predictable: calling it with the same inputs many times should produce the same outputs. It shouldn't perform any side effects like API calls or router transitions. These should happen before an action is dispatched.
- The root reducer may combine the output of multiple reducers into a single state tree.
How you structure the root reducer is completely up to you. More info is in reducers
- The Redux store saves the complete state tree returned by the root reducer.
This new tree is now the next state of your app! Every listener registered with
store.subscribe(listener) will now be invoked; listeners may
store.state to get the current state.
Now, the UI can be updated to reflect the new state.
//TODO link to how to connect to UI in realish app
Note for Advanced Users
If you're already familiar with the basic concepts and have previously completed this tutorial, don't forget to check out async flow in the advanced tutorial to learn how middleware transforms async actions before they reach the reducer.