https://kotlinlang.org logo
#compose
Title
# compose
g

Guy Bieber

06/23/2020, 11:02 PM
It seems like if there was not a user interaction (i.e. updating initial state from the server instead of a user action) the values don’t update. I use the same model for different controls and some work / some don’t.
l

Leland Richardson [G]

06/23/2020, 11:08 PM
just a shot in the dark, but usually when i see people run into this problem it’s because you’re actually creating a new model/state every time you recompose. For instance:
Copy code
@Composable fun Counter() {
  var count = mutableStateOf(0)
  Text("Count: ${count.value}")
  Button(onClick={ count.value++ }) {
    Text("Increment")
  }
}
2
👍 1
ie, what you really want is:
Copy code
@Composable fun Counter() {
  val count = remember { mutableStateOf(0) }
  Text("Count: ${count.value}")
  Button(onClick={ count.value++ }) {
    Text("Increment")
  }
}
which is the same as
Copy code
@Composable fun Counter() {
  val count = state { 0 }
  Text("Count: ${count.value}")
  Button(onClick={ count.value++ }) {
    Text("Increment")
  }
}
so perhaps you’re constructing a model each recompose and you’re only seeing the initial state each time
g

gildor

06/24/2020, 1:42 AM
Had the same issue when just started play with compose. Should usage of eager version of mutable state be discouraged?
state { defaultValue }
even shorter and avoid such accidental introduction of state recreation Or there is some important use case for mutableStateOf?
l

Leland Richardson [G]

06/24/2020, 2:05 AM
mutableStateOf can be used outside of composition, which is an important use case. This is a common source of confusion though so we are throwing around ideas of how to make it less likely to make this mistake
g

gildor

06/24/2020, 2:21 AM
ahh, right, so state is composable itself and cannot be called outside of composable function
Maybe lint check? because usage of it from composable function most probably a mistake
l

Leland Richardson [G]

06/24/2020, 3:01 AM
yep, this is at a minimum something we will do
👍 2