Skip to content

Latest commit

 

History

History
86 lines (64 loc) · 2.71 KB

README.md

File metadata and controls

86 lines (64 loc) · 2.71 KB

RecyclerView DiffUtil Payload demo

Forked from https://github.com/jshvarts/DiffUtilPayloadDemo

The original blog post with an explanation is here RecyclerView DiffUtil with Change Payload

How it works (tap to watch):

Alt text

Code:

class ItemAdapter(
  private val favoriteListener: (String, Boolean) -> Unit
) : ListAdapter<Item, ItemViewHolder>(ItemDiffCallback()) {

...
...

  override fun onBindViewHolder(holder: ItemViewHolder,
                                position: Int,
                                payloads: MutableList<Any>) {
    if (payloads.isEmpty()) {
      super.onBindViewHolder(holder, position, payloads)
    } else {
      if (payloads[0] == true) {
        // change 'favorite' icon state via holder
        holder.bindFavoriteState(getItem(position).isFavorite)
      }
    }
  }

}
class ItemDiffCallback : DiffUtil.ItemCallback<Item>() {

  ...
  ...

  override fun getChangePayload(oldItem: Item, newItem: Item): Any? {
    return if (oldItem.isFavorite != newItem.isFavorite) true else null
  }
}

Jetpack Compose version is available through the branch jetpack-compose-list

Alt text

Code:

      LazyColumn {
                items(
                    items = list,
                    key = { item -> item.id }
                ) { item ->
                    ListItem(item = item, onFavoriteClicked = {
                        onFavouriteClicked(item)
                    })
                }
            }

Follow:

Dmitri Chernysh

Youtube Instagram Twitter Linkedin