Does this code recompose correctly/efficiently, wh...
# compose
p
Does this code recompose correctly/efficiently, when selected index changes? Should I also use
isSelected
as an additional key?
Copy code
val selectedIndex by remember {
    mutableStateOf(2)
}

for (i in 0 until 4) {
    val isSelected = i == selectedIndex
    val text = "$isSelected"
    key(i) {
        Text(text)
    }
}
s
I don’t think adding
key
would change if something recomposes more efficiently, I thought it’d only be for correctness, . But regarding this example here, why not write it like this
Copy code
for (i in 0 until 4) {
  key(i) {
    val isSelected = i == selectedIndex
    val text = "$isSelected"
    Text(text)
  }
}
So that you are sure these 4 separate calls are keyed properly.
p
I was debugging how stuff recomposes and ended up with code like that. Otherwise I agree with you.
I'm wondering, how to use
key
, to make
Text
recompose only if needed. I've tried
key(i, isSelected)
etc.
s
Doesn’t
Text
skip recomposition if the text provided to it is the exact same as it was previously?
If you have “2” selected, and then click on “1", doesn’t 0 and 3 get skipped? Have you tried using the layout inspector to check this out?
p
I guess it should skip, but I'm wondering how I could use this, if I had more complex layout or smth
s
It really depends what you mean. By default things should just work well, provided you give stable parameters to your composables. I’d say start looking into these problems only after you notice there’s issues. Now this already looks like it works properly, so there’s not much to try out right? In any case, I don’t think
key
is where you want to go when you want to limit recompositions, extracting composable functions with stable parameters maybe is the way to go if there’s some recomposition scopes that make way too many composables try to recompose themselves.
👆 1