[TIL] ๐ŸŒผ24/04/13๐ŸŒผ#RecyclerView #payload #DiffUtil

0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
81/104
post-thumbnail
post-custom-banner

[TIL] ๐ŸŒผ24/04/13๐ŸŒผ#RecyclerView #payload #DiffUtil

  • ์˜ค๋Š˜์—ฌํ–‰ ๊ฐœ๋ฐœ ์ค‘ RecyclerView์˜ ํ•ญ๋ชฉ์„ ๋กฑํด๋ฆญํ•˜์—ฌ ๋“œ๋ž˜๊ทธ&๋“œ๋กญํ•˜์—ฌ ์ˆœ์„œ ๋ณ€๊ฒฝํ•˜๋Š” ๊ธฐ๋Šฅ์„ ๊ตฌํ˜„ํ•˜๋ฉฐ, ํ•ญ๋ชฉ์˜ ์ˆœ์„œ๋ฅผ ํ‘œ์‹œํ•˜๋Š” TextView๋งŒ์„ ์ƒˆ๋กœ bindingํ•˜๊ธฐ ์œ„ํ•ด RecyclerView์˜ payload๋ฅผ ์‚ฌ์šฉํ•œ ์ ์ด ์žˆ์—ˆ๋‹ค.
  • ์˜ค๋Š˜์€, ์ด๋ฏธ์ง€ ๊ฒ€์ƒ‰ ์•ฑ์—์„œ RecyclerView์˜ ํ•ญ๋ชฉ์„ ํด๋ฆญํ•˜์—ฌ ์ข‹์•„์š”/์ข‹์•„์š” ์ทจ์†Œ ๊ธฐ๋Šฅ์„ ๋ฆฌํŒฉํ† ๋งํ•˜๋ฉฐ, ํ•ญ๋ชฉ ์ „์ฒด๋ฅผ ๋‹ค์‹œ bindingํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ ์ข‹์•„์š” ์—ฌ๋ถ€๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ํ•˜ํŠธ ๋ชจ์–‘ ImageView๋งŒ์„ ์ƒˆ๋กœ bindingํ•˜๊ณ  ์‹ถ์–ด์ ธ payload๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค.
    • ์ด๋ฒˆ์—๋Š” payload ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ Any()๋ฅผ ์ „๋‹ฌํ•˜๋Š” ๋ฐฉ์‹์ด ์•„๋‹Œ, ๋‹ค๋ฅธ ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ˜„ํ–ˆ๋‹ค!

๐Ÿ“Œ์ฐธ๊ณ ์ž๋ฃŒ:

  • RecyclerView์˜ ListAdpater์— submitList๋กœ ์ƒˆ๋กœ์šด ๋ฐ์ดํ„ฐ ์…‹์„ ์ „๋‹ฌ
    -> DiffUtil์—์„œ getChangePayload ํ•จ์ˆ˜๋กœ payload ๋ฐ˜ํ™˜
    -> onBindViewHolder์—์„œ payload ์ข…๋ฅ˜์— ๋”ฐ๋ผ ํ™€๋” binding ๊ฐ€๋Šฅ!
  • ItemDiffCallback.kt
import androidx.recyclerview.widget.DiffUtil
import com.sparta.imagesearch.data.Item

sealed interface ItemChangePayload {
    data class FolderIdChange(val folderId: String) : ItemChangePayload
}

object ItemDiffCallback : DiffUtil.ItemCallback<Item>() {
    override fun areItemsTheSame(oldItem: Item, newItem: Item): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: Item, newItem: Item): Boolean {
        return oldItem == newItem
    }

    override fun getChangePayload(oldItem: Item, newItem: Item): Any? {
        return when {
            oldItem.folderId != newItem.folderId ->
                ItemChangePayload.FolderIdChange(newItem.folderId)

            else -> super.getChangePayload(oldItem, newItem)
        }
    }
}
  • ItemAdapter.kt
    override fun onBindViewHolder(holder: Holder, position: Int) {
        holder.bind(currentList[position])
    }

    override fun onBindViewHolder(holder: Holder, position: Int, payloads: MutableList<Any>) {
        when(val lastPayload = payloads.lastOrNull()){
            is ItemChangePayload.FolderIdChange ->
                holder.bindHeartImageView(lastPayload.folderId)

            else -> super.onBindViewHolder(holder, position, payloads)
        }
    }
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€