I have a list of data classes that I am displaying...
# compose
a
I have a list of data classes that I am displaying using a LazyColumn. But even when a single item in the list changes, all the items inside LazyColumn are recomposed. I thought marking the data class as
@Immutable
might fix the issue but it didn't. How can I prevent these unnecessary recompositions? Code in 🧵
Copy code
@Immutable
data class EqualSplit(
    val name: String,
    val image: String,
    val number: String,
    val selected: Boolean
)
Copy code
// In View Model
val equalSplits = mutableStateListOf<EqualSplit>()

fun onSplitSelectionChange(index: Int) {
    equalSplits[index] = equalSplits[index].let { it.copy(selected = !it.selected) }
}
Copy code
LazyColumn {
    itemsIndexed(viewModel.equalSplits)  { index, split ->
        EqualSplitRowItem(
            split = split,
            onSelectionChange = { viewModel.onSplitSelectionChange(index) }
        )
    }
}

@Composable
private fun EqualSplitRowItem(
    split: EqualSplit,
    onSelectionChange: () -> Unit,
    modifier: Modifier = Modifier
) {
    Log.d("TAG", split.name) // This is printed for all items when any of the items change
    Row(
        modifier = modifier
            .clickable(onClick = onSelectionChange)
    ) {
        ...
    }
}
j
You need to provide an implementation for the key function on itemsIndexed
☝️ 1
a
I updated my
itemsIndexed
to this:
Copy code
itemsIndexed(
    items = viewModel.equalSplits,
    key = { _, split -> split.number }
) { index, split ->
    EqualSplitRowItem(
        split = split,
        onSelectionChange = { viewModel.onSplitSelectionChange(index) }
    )
}
It didn't work :( @Adam Powell Does it have to do something with the
onSelectionChange
lambda? Is it possible that Compose doubts the lambda might have changed and so it always recomposes everything??