quantum
State management library for Android.
Quantum is a general purpose state management library designed for building easy, stable and thread safe Android applications. It was inspired by AirBnb's MvRx and tailored for building reliable ViewModels.
Usage
gradle
Define a State
States should always be immutable. I highly recommend using
kotlin data classes to make immutability easy ?
Example:
Create a Quantum
A Quantum is the owner of your state. It applies all reducers,
invokes actions and publishes new states.
Example:
Enqueue a Reducer
Reducers are functions that take the current state and create a new state.
Reducers will always be called by a internal thread of the Quantum
.
Only one reducer will run at a time!
Reducers are allowed to return the same (untouched) instance to signal a no-operation.
Example (simple reducer):
A simple reducer that that says hello to a certain user.
Unlike other "State Owner" concepts, Quantum allows reducers to dispatch async operations.
This decision was made to give developers the option to handle side-effects
inside a safer environment.
Example (load content):
Much more complicated reducer problem:
We want to
- Load content from repository asyncronously
- Ensure that only one loading operation is running at a time
- Publish the content when fetched successfully
- Publish the error when an error occurred
Enqueue an Action
Actions are parts of your code that require the most recent state, but do not intend to change it.
Actions will always be called by a internal thread of the Quantum
and run after
all reducers are applied.
Listen for changes
Listeners are invoked by Android's main thread by default.
It is possible to configure the thread which invokes listeners by specifying an Executor.
Example: Without Extensions, Rare
Example: Without Extensions, Function
Example: Rx (recommended)
Nested Quantum / Map
It is possible to map a Quantum to create a 'Child-Quantum' which can enqueue reducers and actions
as usual. The state of this child will be in sync with the parent Quantum.
Example: Child
Debugging
History
It is possible to record all states created in a Quantum
.
Quitting
A Quantum
has to be stopped if it's no longer needed, in order to stop the internal background
thread and release all resources.
ViewModel (Suggestion)
I suggest having one 'ViewState' for each ViewModel. The ViewModel itself
might want to implement Quantum
itself.
Example:
Configuration
It is possible to configure the defaults of Quantum for your whole application.
For example: It is possible to specify the default threading mode, history settings,
or even the thread pool that is shared for multiple Quantum instances.