MobX for Kotlin

Additional

Language
Kotlin
Version
0.1 (Jun 19, 2020)
Created
Feb 18, 2020
Updated
Nov 10, 2020 (Retired)
Owner
RomanPozdeev
Contributors
RomanPozdeev
Dharmendra Pratap Singh (dp-singh)
2
Activity
Badge
Generate
Download
Source code

MobX for Kotlin

Core concepts of MobX

Observable

Observable is a mutable value that notifies about its changes.

class Task(val id: Int, title: String, description: String, done: Boolean = false) {
    var title by observable(title)

    var description by observable(description)

    var done by observable(done)
}

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 count by computed { todoList.size }
    val pending by computed { todoList.count { !it.done } }
    val done by computed { count - pending }

Autorun

Autorun runs a reaction when its dependencies (observables and computed) are changed.

val disposable = autorun {
    containerView.title.text = task.title
    containerView.description.text = task.description
}

In this example logging runs immediately and then on any change of task title or task description. 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 clear() = action {
    todoList.clear()
}

or

fun clear() = action("clearAllTasks") {
    todoList.clear()
}

A string argument of action is a payload. It can be used for logging.

Usage:

Please check out app

or

Add it in your root build.gradle at the end of repositories:

Step 1. Add the JitPack repository to your build file

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

Step 2. Add the dependency

dependencies {
    implementation 'com.github.RomanPozdeev:MobX:0.1'
}

More