Question: Is there a way to prevent recomposition ...
# compose
j
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
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
You can try to use
distinctUntilChanged
j
Because it’s unnecessary work done if the data is the same. This is what intelligent recomposition is meant to prevent. See the
MovieOverView
example here: https://developer.android.com/jetpack/compose/lifecycle#add-info-smart-recomposition Even if we add an item to the beginning of the list (shifting all previous items down), because we set a
key
which maps to the ID of the item, the existing instance should be able to be used. I.e. no recomposition
@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
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
Thanks @Filip Wiesner. You’re probably right. I’ll look into this some more