supermar10
supermar10

Reputation: 145

Jetpack compose doesn't recompose on mutableStateOf change

I wanted to build a very simple demo. A button which you can click, and it counts the clicks.

Code looks like this:

class MainActivity : ComponentActivity() {
    private var clicks = mutableStateOf(0)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
           Surface(color = MaterialTheme.colors.background) {
                NewsStory(clicks.value) { onClick() }
           }
        }
    }

    private fun onClick() {
        clicks.value++
    }
}

@Composable
fun NewsStory(clicks: Int, onClick: () -> Unit) {
    Column(modifier = Modifier.padding(8.dp)) {
        Button(onClick = onClick) {
            Text("Clicked: $clicks")
        }
    }
}

From my understanding this should be recomposed everytime the button is clicked, as clicks is changed.

But it does not work, any ideas what I'm doing wrong here?

I'm on androidx.activity:activity-compose:1.3.0-beta01, kotlin 1.5.10 and compose version 1.0.0-beta08

Upvotes: 3

Views: 5740

Answers (1)

Code Poet
Code Poet

Reputation: 8013

You need to use the "remember" keyword for the recomposition to happen each time, as explained here: https://foso.github.io/Jetpack-Compose-Playground/general/state/

In short, your composable would look like this:

    @Composable
fun NewsStory (){
val clickState = remember { mutableStateOf(0) }
Column (modifier = Modifier.padding(8.dp)) {
        Button(
            onClick = { clickState.value++ }) {
        }
        Text("Clicked: $clickState.value.toString()")
    }
}

Upvotes: 3

Related Questions