Question: Is there a way to prevent recomposition for a list of
Strings
from
LiveData
? When the items are sorted it should not cause recomposition. But seems like
observeAsState
forces recomposition every time. Even though I’m using
key
Copy code
val value by viewModel.data.observeAsState()
LazyColumn {
value?.forEach {
item(key = it) {
Text( text = "$it!")
}
}
}
f
Filip Wiesner
10/15/2021, 9:12 AM
Every LiveData emit will trigger recomposition:
Every time there would be new value posted into the
LiveData
the returned
State
will be updated causing recomposition of every
State.value
usage.
If you don't want your Composable to recompose, make sure the LiveData does not emit new value. I haven't touched LiveData for a while so I don't know how it behaves.
But in the end you shouldn't care about when your component recomposes in most cases. Why do you want to prevent the recomposition?
d
divid3d
10/15/2021, 9:19 AM
You can try to use
distinctUntilChanged
j
Johnny
10/15/2021, 9:19 AM
Because it’s unnecessary work done if the data is the same.
This is what intelligent recomposition is meant to prevent. See the
which maps to the ID of the item, the existing instance should be able to be used. I.e. no recomposition
Johnny
10/15/2021, 9:24 AM
@divid3d I probably should have explained the scenario better. It would be new data. It’s just the new data is the sorted list of the original data. And my understanding is re-ordering shouldn’t cause recomposition again. E.g.
Copy code
// list emitted
banana
apple
orange
// list emitted 2nd time
apple
banana
orange
f
Filip Wiesner
10/15/2021, 9:32 AM
Correct me if I'm wrong but I think
key
is not really meant to prevent recomposition (even thought it might have that effect sometimes) but rather to keep the same composition instance - e.g. keeping correct instances inside
remember
.
👍 2
mind blown 1
j
Johnny
10/15/2021, 9:54 AM
Thanks @Filip Wiesner. You’re probably right. I’ll look into this some more