Reputation: 668
How to update, delete or add item in a LazyColumn
in Jetpack Compose ?
Which is easily achieve by adapter.notifydatasetchange
or diffutils
in recyclerview
Upvotes: 4
Views: 5905
Reputation: 5255
Just do exactly that on the collection you are passing to items
function. This is simple as that. If your class is stable (just use data class
) you are fine, it will just work. Welcome to Compose magic.
If you want the best performance on update/delete/add then expose a stable key in the items
function, see here for more details: https://developer.android.com/jetpack/compose/lists#item-keys
Example:
@Composable
fun MessageList(messages: List<Message>) {
LazyColumn {
items(
items = messages,
key = { message ->
// Return a stable + unique key for the item
message.id
}
) { message ->
// Display entry here
MessageRow(message)
}
}
}
Here, if you provide the key lambda, the compose will know that this entry is the same entry - just with different content. If you do not provide this lambda - index in list will be used as key. So any addition other than at the end of the list would trigger a lot of recompositions. So it is more or less like a diff utils. You only have to provide this, because content equality is handled by compose implicitly - via equals
of the Message
object.
So if you want to remove one message from the list - remove it and pass new list to MessageList
. Compose will handle the rest for you
Upvotes: 1