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 syntaxLaunchedEffect
, 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