Sudhir Singh Khanger
07/22/2021, 4:26 AMremeber
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.rajesh
07/22/2021, 6:36 AMHalil Ozercan
07/22/2021, 7:04 AMvalue
inside MutableState
which would surely trigger a recomposition.Tobias Suchalla
07/22/2021, 7:08 AMval state: MutableState<Int> _*by*_ remember { mutableStateOf(1) }
. In that case he indeed could not reassign the state unless he changed it to var
.rajesh
07/22/2021, 7:12 AMjulioromano
07/22/2021, 7:27 AMval 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.