从 Room 的 Livedata 设置非空列表后,OnBindViewHolder() 不调用

OnBindViewHolder() doesn't call after setting unempty list from Room's Livedata

我发现了类似的问题,但没有涉及房间。

所以我在整个 DAO-Repository-ViewModel(房间版本 2.2.3)中使用 LiveData:

@Query("SELECT * from ...")    
fun getGoods(): LiveData<List<Goods>>

在我的片段中有订阅:

mViewModel.goodsList.observe(viewLifecycleOwner, Observer {goodsList ->            
        mAdapter.setList(goodsList)            
    })

使用 logcat 我可以看到列表不为空。 RecyclerView Adapter 的 setList() 列表也不为空。

fun setList(goodsList: List<Goods>) {
    records = goodsList        
    notifyDataSetChanged()
}

但是没有调用 onBindViewHolder() 方法

override fun onBindViewHolder(viewHolder: ViewHolder, i: Int) {
    // I can't get there
    viewHolder.bind(records[i])
}

我找到了 2 种解决问题的方法,但它们都是 hack-like,我想了解更好的方法:

  1. 在片段中添加延迟获取 LiveData 的 onChange():

    Handler().postDelayed({mAdapter.setList(goodsList)}, 200)

  2. 切换上下文与协程的 Dispatchers.Main 在片段中获取 LiveData 的 onChange()。

我的错误在哪里?

这个:

fun setList(goodsList: List<Goods>) {
    records = goodsList        
    notifyDataSetChanged()
}

应该是:

fun setList(goodsList: List<Goods>) {
    records.clear()
    records.addAll(goodsList)       
    notifyDataSetChanged()
}

但是我会考虑使用 ListAdpter https://developer.android.com/reference/android/support/v7/recyclerview/extensions/ListAdapter.htmlDiffUtil.ItemCallback<Goods> 回调。