Suman Radhakrishnan
Suman Radhakrishnan

Reputation: 668

Equivalent to adapter.notifydatasetchange or Diffutils in Jetpack Compose Lazy Column/Row

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

Answers (1)

Jakoss
Jakoss

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

Related Questions