3

我正在尝试使用 android Paging 3(版本 3.0.0-SNAPSHOT)从 Room 数据库(无远程数据源)中分页数据。

最初页面加载数据成功,但是当一个新的“条目”添加到数据库中并且我返回到这个页面时,collectLatest 被触发但没有加载数据(“pagingData”条目列表为空)

这是我的查询:

   @Query("SELECT * FROM entry ORDER BY dateTime DESC")
  fun getAll() : PagingSource<Int, Entry>

这是我的视图模型:

 val flow = Pager(
    PagingConfig(pageSize = 20)
) {
    entryDao.getAll()
}.flow
   .cachedIn(viewModelScope)

在我的片段中,我正在观察这样的数据:

iewLifecycleOwner.lifecycleScope.launch {
        homeViewModel.flow.collectLatest { pagingData ->
            adapter.submitData(pagingData)
        }
    }

这是我的适配器:

class EntriesAdapter( val context : Context, private val onClick: (String)->Unit) :
    PagingDataAdapter<Entry , RecyclerView.ViewHolder>(diffCallback)
{
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EntryViewHolder
            = EntryViewHolder(
     DataBindingUtil.inflate(
            LayoutInflater.from(parent.context),
            R.layout.item_entry, parent, false
        ) , onClick)

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        var entry = getItem(position)
        if (entry != null) {
            (holder as EntryViewHolder).bindTo(entry);
        }
    }

    companion object {
        //This diff callback informs the PagedListAdapter how to compute list differences when new
        private val diffCallback = object : DiffUtil.ItemCallback<Entry>() {
            override fun areItemsTheSame(oldItem: Entry, newItem: Entry): Boolean =
                oldItem.id == newItem.id

            override fun areContentsTheSame(oldItem: Entry, newItem: Entry): Boolean =
                oldItem.id == newItem.id
        }
    }
    inner class EntryViewHolder( val binding : ItemEntryBinding ,val onCLick:
        (String)->Unit ) : RecyclerView.ViewHolder(binding.root) {
        var entry:Entry? = null
        fun bindTo(entry: Entry) {
            this.entry = entry
            with(binding) {
                entryItem = entry
                cardView.setOnClickListener{
                    onCLick
                }
              
                executePendingBindings()
            }
        }
    }
}
4

1 回答 1

1

我遇到了和你类似的问题,只是entriesAdapter.refresh()在添加新项目后忘记打电话了。

于 2020-11-02T12:42:49.523 回答