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

Sudhir Singh Khanger

07/22/2021, 4:26 AM
1. Is a variable cached by
remeber
function only initialized during
Initial Composition
or is it always initialized during
recomposition
but with the last saved value? 2. Is 
val state: Int = remember { 1 }
 as good as 
val state: Int = 1
 because in both cases 
state
 variable is immutable and once it is initialized it can only be read? 3. In
val state: MutableState<Int> = remember { mutableStateOf(1) }
, can you do something like
state.value = 2
to change value of state and which would trigger recomposition.
🙌 1
r

rajesh

07/22/2021, 6:36 AM
1. It only initialised once during initial composition 2. It's not same. val state: Int = 1 will get assigned to state variable every time during recomposition. 3. You can't change value of val, but you can do it for var and recomposition will be triggered.
h

Halil Ozercan

07/22/2021, 7:04 AM
@rajesh I'm not sure about the 3rd point. He is changing the
value
inside
MutableState
which would surely trigger a recomposition.
t

Tobias Suchalla

07/22/2021, 7:08 AM
+1. It would be a different story if he used delegation:
val state: MutableState<Int> _*by*_ remember { mutableStateOf(1) }
. In that case he indeed could not reassign the state unless he changed it to
var
.
r

rajesh

07/22/2021, 7:12 AM
@Halil Ozercan yes, sorry for my mistake.
j

julioromano

07/22/2021, 7:27 AM
val state: Int = remember { 1 }
I feel answer to 1 is actually “always initialized during 
recomposition
 but with the last saved value”. remember will save “1" in the slot table during composition. In subsequent recompositions remember will read the “1” from the slot table and assign it to the
state
val So during composition and recomposition the state val will always be assigned a 1. The difference is wether this 1 comes from running the lambda (happens during composition) or is read from the slot table (happens during recomposition). ------------- Answer to 2 is yes IMHO, because in case of very simple computations in the lambda (like in this case returning a “1" constant) reassigning a constant every recomposition or saving and reading it from the slot table will not lead to significant performance differences. Of course this is valid only if the lambda contains a very trivial computation. When the lambda starts to become computationally intensive the advantage of running it just once and storing it’s result in the slot table will be tangible.
1
3 Views