代码之家  ›  专栏  ›  技术社区  ›  Damia Fuentes

使用分页库更新单个元素的最佳方法

  •  5
  • Damia Fuentes  · 技术社区  · 7 年前

    使用新的分页库时,更新单个元素的最佳方法是什么?

    假设我们有 Paging with network 使用 PageKeyedSubredditDataSource 。假设我们想改变 RedditPost . 所以,我们想检查它是否在列表中,如果在,就更新它。更新不应该像调用invalidate()那样简单,它将调用第一个页面(可能redditpost在第五个页面中)。我们不想更新所有元素,只更新一个)。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Damia Fuentes    7 年前

    请注意,所有这些都在 Paging with network 谷歌示例。尽管如此,这个想法还是存在的。

    @萨奎拉帮我解决了这个问题。将这些类添加到项目中。基本上我们在扩展 ViewHolder 成为 LifeCycle Owner ,因为默认情况下已使用 Activities Fragments .

    这个 LifecycleViewHolder :

    abstract class LifecycleViewHolder(itemView: View) :
            RecyclerView.ViewHolder(itemView),
            LifecycleOwner {
    
        private val lifecycleRegistry = LifecycleRegistry(this)
    
        fun onAttached() {
            lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
        }
    
        fun onDetached() {
            lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
        }
    
        override fun getLifecycle(): Lifecycle = lifecycleRegistry
    }
    

    LifecycleOwner 是表示类具有 Lifecycle 。你可以找到更多的信息 here .

    这个 LifecyclePagedListAdapter :

    abstract class LifecyclePagedListAdapter<T, VH : LifecycleViewHolder>(diffCallback: DiffUtil.ItemCallback<T>) :
            PagedListAdapter<T, VH>(diffCallback) {
    
        override fun onViewAttachedToWindow(holder: VH) {
            super.onViewAttachedToWindow(holder)
            holder.onAttached()
        }
    
        override fun onViewDetachedFromWindow(holder: VH) {
            super.onViewDetachedFromWindow(holder)
            holder.onDetached()
        }
    }
    

    这个 LifecycleAdapter (如果你需要的话):

    abstract class LifecycleAdapter<VH : LifecycleViewHolder> :
            RecyclerView.Adapter<VH>() {
    
        override fun onViewAttachedToWindow(holder: VH) {
            super.onViewAttachedToWindow(holder)
            holder.onAttached()
        }
    
        override fun onViewDetachedFromWindow(holder: VH) {
            super.onViewDetachedFromWindow(holder)
            holder.onDetached()
        }
    }
    

    然后,延伸 MyAdapter LifecyclePagedListAdapter<MyEntity, LifecycleViewHolder>(MY_COMPARATOR) MyViewHolder LifecycleViewHolder(view) 。你必须根据我们所做的相应改变来完成你的课程。现在我们可以观察到 liveData 对象打开 我的观众 上课。所以我们可以把这个加到 我的观众 类(假设您正在使用依赖项注入)。基本上,我们也会这么做 碎片 活动 :

    private lateinit var myViewModel: MyViewModel
    
    init {
        (itemView.context as? AppCompatActivity)?.let{
            myViewModel = ViewModelProviders.of(it).get(MyViewModel::class.java)
        }
    }
    

    然后,在 bind() 方法:

    fun bind(myCell: MyEntity?) {
        myViewModel.myLiveData.observe(this, Observer {
            // Buala!! Check if it is the cell you want to change and update it.
            if (it != null && myCell != null && it.id == myCell.id) {
               updateCell(it)
            }
        })
    }
    
    推荐文章