This is a very simple sample that demonstrates capabilities of MobX for Kotlin. Disclaimer: I am not an author of this library.
Observable is a mutable value that notifies about its changes.
var appleCount by observable(0)
var bananaCount by observable(0)
Computed is a read-only value that is automatically kept in sync with other observables and computed. Just like an observable, computed value notifies about its changes.
val fruitCount by computed { appleCount + bananaCount }
Autorun runs a reaction when its dependencies (observables and computed) are changed.
val disposable = autorun {
Log.d("FRUITS", "Apples: ${appleCount}, bananas: ${bananaCount}, fruits: ${fruitCount}")
}
In this example logging runs immediately and then on any change of appleCount, bananaCount or fruitCount. There are no needs to subscribe to these observables manually! Another example of reaction is UI updating.
Actions allow to mutate observables. Actions batch mutations, so a notifications will occur only after an action has finished.
fun reset() = action("reset") {
appleCount = 0
bananaCount = 0
}
A string argument of action is a payload. It can be used for logging.
- FruitCounter is a domain object with observable state and actions.
- FruitCounterViewModel converts domain state to UI state and calls actions of FruitCounter.
- localized_string is a wrapper on top of string resources. It allows to make formatting in ViewModels rather than in acitivities.
- FruitCounterActivity observes FruitViewModel with a helper method observe. This method works as
autorun
but manages subscriptions automatically according to a lifecycle. - Action logging is configured in FruitCounterApplication.
- https://mobx.js.org/intro/concepts.html - original MobX documentation
- https://github.com/mobxjs/mobx.dart - MobX for Dart/Flutter
- https://hackernoon.com/becoming-fully-reactive-an-in-depth-explanation-of-mobservable-55995262a254 - an in-depth explanation of MobX