update policy for a data class in Android Jetpack Compose

Viewed 743

I try to use an object from a data class that will update a Composable and declare it as follows:

data class CounterState(var counter: Int = 0)
.....
val counterState: CounterState by remember { mutableStateOf(CounterState(), structuralEqualityPolicy()) }

structuralEqualityPolicy() is the update policy of the Composable and is defined :

A policy to treat values of a MutableState as equivalent if they are structurally (==) equal.

if the property counter changes like with: counterState.counter++ the Composable should be updated, but this does not work.

I use Compose version 1.0.0-alpha06

Any Idea how to resolve the issue?

import androidx.compose.foundation.Text
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Button
import androidx.compose.runtime.*
import androidx.ui.tooling.preview.Preview

data class CounterState(var counter: Int = 0)

@Composable
fun dataClassRemember() {
    val counterState: CounterState by remember { mutableStateOf(CounterState(), structuralEqualityPolicy()) }
    Column() {
        Button(onClick = {
            counterState.counter++
        }) {
            Text(text = "Increment")
        }
        Text(text = "Counter value is ${counterState.counter}")
    }
}

@Preview("dataClassRemember")
@Composable
fun dataClassRememberPreview() {
    dataClassRemember()
}
2 Answers

I would try this instead:

data class CounterState(var counter: Int by remember { mutableStateOf(0)})

Hope it works, Anna

Since the composable is observing on the MutableState<CounterState>

val counterState: CounterState by remember { mutableStateOf(CounterState(), structuralEqualityPolicy()) }

When we do counterState.counter++, the state variable never changes i.e the address of the object is the same.

Suppose if we do something like this

counterState.value = CounterState()

This would trigger a state change.

Related