Search code examples
androidrecompose

Remember, not to work as well and restart


Recently I faced a problem with remember in compose; I have two simple, composable functions like the below:

@Composable
fun foo() {
    var x = remember { 1 }
    x += 1
    Text("$x")
}

@Composable
private fun MainScreen() {
    var state by remember { mutableStateOf(1) }
    Column {
        foo()
        Button(onClick = { state += 1 }) {
            Text("Update Offer $state")
        }
    }
}

I expect that when clicking the button occurs, foo() recompose, and x increases, but this isn't work, and the x is always 2. Can anyone explain why it doesn't work as I expected?


Solution

  • You are using remember to store the initial value of x as 1. Remember is a composable function that returns a value that is remembered across recompositions. This means that x will not change unless the key changes. In your case, the key is always 1, so x will always be 1 + 1 = 2.

    You should use mutablestate for x instead of remember. Mutablestate is a way to store values that can be changed and trigger recomposition when they do. You can use mutableStateOf to create a mutable state and delegate the getter and setter of the state.