Skip to content

aartikov/MobX-Samples

Repository files navigation

MobX for Kotlin sample

About

This is a very simple sample that demonstrates capabilities of MobX for Kotlin. Disclaimer: I am not an author of this library.

Core concepts of MobX

Observable

Observable is a mutable value that notifies about its changes.

var appleCount by observable(0)
var bananaCount by observable(0)

Computed

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

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.

Action

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.

Sample

screenshot

  • 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.

Futher reading

Releases

No releases published

Packages

No packages published

Languages