hamid Mahmoodi
hamid Mahmoodi

Reputation: 718

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?

Upvotes: 0

Views: 1396

Answers (2)

hamid Mahmoodi
hamid Mahmoodi

Reputation: 718

As Ammirhossein said, the problem was that remember works with reference and remember { 1 } always returns 1; for fix the problem, I changed the code a little as below:

data class Test(var value: Int)
var temp = Test(1)
@Composable
fun foo(state: Int) {
    var x = remember { temp }
    Column {
        Text("$x")
        Text("${temp.value}")
    }
}

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

Upvotes: 0

Amirhosein
Amirhosein

Reputation: 4446

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.

Upvotes: 2

Related Questions