sofnomic cr
sofnomic cr

Reputation: 322

How to remember state of a class not primary type in jetpack compose

Hi developers in jetpack compose if i do this:

var model by remember{ mutableStateOf(false)}

It works !!

but why if i do this:

 var model by remember{ mutableStateOf(Register())}

Register is a class:

class Register {
    var correo: String=""
    var password: String=""
    var nombre: String=""
    var apellido: String=""
    var direccion: String=""
    var telefono: String=""
    var confirmacion: String=""
}

but the second way is not binding properties How can i do that?

Upvotes: 1

Views: 1456

Answers (1)

Thracian
Thracian

Reputation: 66674

For Compose to trigger recomposition you need to change value of

 var model by remember{ mutableStateOf(Register())}

because by default mutableStateOf uses SnapshotMutationPolicy that checks if two instances are equal

fun <T> mutableStateOf(
    value: T,
    policy: SnapshotMutationPolicy<T> = structuralEqualityPolicy()
): MutableState<T> = createSnapshotMutableState(value, policy)
fun <T> structuralEqualityPolicy(): SnapshotMutationPolicy<T> =
    StructuralEqualityPolicy as SnapshotMutationPolicy<T>

private object StructuralEqualityPolicy : SnapshotMutationPolicy<Any?> {
    override fun equivalent(a: Any?, b: Any?) = a == b

    override fun toString() = "StructuralEqualityPolicy"
}

You can either do this by creating a new SnapshotMutationPolicy or

setting new Register instance to your model. I think easiest way is to use a data class and create a new instance with data class copy function which creates a new instance allowing you to alter some of its properties while keeping the rest unchanged

data class Register (
    var correo: String=""
    var password: String=""
    var nombre: String=""
    var apellido: String=""
    var direccion: String=""
    var telefono: String=""
    var confirmacion: String=""
)

var model by remember { mutableStateOf(Register()) }

model = model.copy(password = "new password")

Upvotes: 2

Related Questions