Travis Griggs
02/24/2023, 8:43 PMCasey Brooks
02/24/2023, 9:03 PMLaunchedEffect(selectedIndex) { }
is probably the easiest way. The block will get called anytime selectedIndex
changes. The SideEffect
function isnât particularly useful for most things youâd want to do in ComposeTravis Griggs
02/24/2023, 9:37 PMvar selectedIndex = remember { mutableStateOf(1) }
LaunchedEffect(selectedIndex) { onSelect(selectedIndex.value) }
?Casey Brooks
02/24/2023, 9:40 PM.value
does. So in this case, youâd do:
val selectedIndex = remember { mutableStateOf(1) }
LaunchedEffect(selectedIndex.value) { onSelect(selectedIndex.value) }
Itâs more common to use the property delegate for state variables though, which simplifies it a bit:
var selectedIndex by remember { mutableStateOf(1) }
LaunchedEffect(selectedIndex) { onSelect(selectedIndex) }
Travis Griggs
02/24/2023, 9:43 PMCasey Brooks
02/24/2023, 9:54 PMmutableStateOf()
variables are what tell Compose when the âcurrent stateâ has changed, which initiates ârecompositionâ that actually updates whatâs visible on the screen. The compiler magic wires up those mutableStateOf()
variables to help the Compose Runtime with that recomposition process.
For the mutableStateOf()
variables themself, itâs basically just a box that holds a value. It can be helpful to look at the actual types in this case, to understand the difference between the two snippets:
val selectedIndex: MutableState<Int> = remember { mutableStateOf(1) }
val selectedIndex: Int by remember { mutableStateOf(1) }
Using the by
keyword is a Kotlin property delegate that simply calls MutableState<T>.value
. And itâs inline, so theres literally no difference between the two, itâs just a simpler syntaxCasey Brooks
02/24/2023, 9:57 PMLaunchedEffect
, consider what it means in the context of âthe current stateâ.
If you passed MutableState<Int>
as the key of LaunchedEffect
, nothing will ever happen because the box itself never changes. But as the value inside the box changes, the Compose recomposition detects the change and ârecomposesâ, at which point the LaunchedEffect
can see that the current is not the same as the previous one, and then runs its block.Travis Griggs
02/24/2023, 10:07 PMCasey Brooks
02/24/2023, 10:13 PMremember(key) { }
, other types of effects). But like most things, the more you work with it, the more it will make sense, so itâs just a matter of playing around with the code and seeing how it behaves. The CodeLab does a great job of walking you through the basics and explaining whatâs going on and how to do things properlyTravis Griggs
02/24/2023, 10:20 PM