Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update policy for a data class in Android Jetpack Compose

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()
}
like image 498
Jean G Avatar asked Feb 03 '26 10:02

Jean G


1 Answers

I would try this instead:

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

Hope it works, Anna

like image 103
Anna The Droid Avatar answered Feb 06 '26 02:02

Anna The Droid