Home > Back-end >  Why do I assign data directly to MutableState variable?
Why do I assign data directly to MutableState variable?

Time:09-17

I was told that MutableState just like MutableLiveData in Kotlin, and MutableState fit Compose, MutableLiveDataenter code here fit XML layout.

In Code A, I need to assign data to bb.value, but why do I assign directly to aa ?

Code A

private var aa by mutableStateOf(-1)

private var bb= MutableLiveData<Int>(-1)  

fun onEditDone() {
    aa = 2
    bb.value = 2
}

CodePudding user response:

It's because of Kotlin's delegation feature where you delegate values using by keyword.

Simple implementation for remember and mutableState, to display how it works when you build something similar to that, is as

// Delegation Functions for setting and getting value
operator fun <T> State<T>.getValue(thisObj: Any?, property: KProperty<*>): T = value

operator fun <T> MutableState<T>.setValue(thisObj: Any?, property: KProperty<*>, value: T) {
    this.value = value
}

/*
 *  State
 */
interface State<out T> {
    val value: T
}
interface MutableState<T> : State<T> {
    override var value: T
}

class MutableStateImpl<T>(value: T) : MutableState<T> {
    override var value: T = value
}

fun <T> mutableStateOf(value: T): MutableState<T> = MutableStateImpl(value)

/*
 *  Remember
 */

inline fun <T> remember(calculation: () -> T): T {
    return calculation()
}

And you can use it as

fun main() {

    val isSelected: MutableState<Boolean> = remember { mutableStateOf(true) }
    isSelected.value = false

    var selected by remember { mutableStateOf(false) }
    selected = false
}
  • Related