What isn't working?
# compose
b
What isn't working?
n
Both: 1. The delayed welcome message 2. The counter when the Button is pressed.
Ok. I found a solution…
Copy code
val count = remember { mutableStateOf(0) }
val welcomeMsg = remember { mutableStateOf("") }
Now I need an explanation 😄
g
Because you recreated
mutableStateOf(0)
on every composition
if you want state survive recomposition, use
remember
👏 1
💡 1
n
thanks @gildor. I saw this discussion and once
state
is deprecated, I thought the
mutableStateOf
will work as the same way. Now makes sense 😉
g
Have you tried to apply auto fix for state?
n
What’s that? Is it a AS feature? 🤔
g
IntelliJ + Kotlin Plugin
n
No I din’t 😩
n
Is there another way to simulate the needs of
remember
?
g
what do you mean “simulate” it?
n
I mean a simple example where
remember
is required.
Maybe I need to understand the concept of “recomposition”. I thought that “recomposition = composable is updated after the state changes”. But I’m clearly wrong
g
see, you should understand that any change which cause recomposition (such as state change) will call your compose function again
if you see on your code, you will see that without remember it means that`count` and
welcomeMsg
will bew set to default value
to avoid this, save this internal state of composable, you can use remember, which saves state, and init default value only first access
n
I got that. but why do I need the
remember
when I’m using that
launch
and I don’t need it when I simply change the state.
I both cases I’m changing the state of the composable and (in theory) the function is called again.
g
change state where?
a side note, you don’t need
withContext
around
delay
n
I know… It was just to simulate an IO operation 🙂
g
what do you mean that you don’t need remember there, isn’t your coroutine changes mutable state?
n
Now the thing is more weird… this example is working 😄
Copy code
@Composable
fun Demo10() {
    val scope = rememberCoroutineScope()
    Log.d("NGVL", "Here")
    val state = mutableStateOf(0)
    Button(
        onClick = {
            scope.launch {
                withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
                    delay(1_000)
                }
                state.value = state.value + 1
            }
        },
        content = {
            Text(text = "Click ${state.value}")
        }
    )
}
without remember 😕
g
it’s just avoids recomposition, if something else will cause it, you will lost your state
not really sure honestly
but any external change also may cause your Demo10 to recompose
r
state{} is just remember{mutableStateOf()} btw
n
but
state
is deprecated 😕
r
Yes
g
yes, so you have to use remember { mutableStateOf() }
Read doc of state function, it has pretty good explanation
n
so why my last snippet is working without the
remember
? 😕
g
Probably because it causes recomposition of Button + Text only
n
yeah… I guess so…
g
It acutally recomposes only Text, not even Button. This state it used only there