android - 如何将 PagedListAdapter 与多个 LiveData 一起使用
问题描述
我有一个带有PagedListAdapter的回收站视图。
在onCreate我有这个代码:
viewModel.recentPhotos.observe(this, Observer<PagedList<Photo>> {
photoAdapter.submitList(it)
})
最近的照片是这样初始化的:
val recentPhotosDataSource = RecentPhotosDataSourceFactory(ApiClient.INSTANCE.photosClient)
val pagedListConfig = PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setInitialLoadSizeHint(INITIAL_LOAD_SIZE)
.setPageSize(PAGE_SIZE)
.build()
recentPhotos = LivePagedListBuilder<Int, Photo>(recentPhotosDataSource, pagedListConfig)
.setFetchExecutor(Executors.newSingleThreadExecutor())
.build()
它工作正常。
接下来,我有search()功能:
private fun searchPhotos(query: String) {
viewModel.recentPhotos.removeObservers(this)
viewModel.searchPhotos(query)?.observe(this, Observer {
photoAdapter.submitList(it)
})
}
viewModel.searchPhotos看起来像这样:
fun searchPhotos(query: String): LiveData<PagedList<Photo>>? {
val queryTrimmed = query.trim()
if (queryTrimmed.isEmpty()) {
return null
}
val dataSourceFactory = SearchPhotosDataSourceFactory(ApiClient.INSTANCE.photosClient, queryTrimmed)
val livePagedList = LivePagedListBuilder(dataSourceFactory, PAGE_SIZE)
.setFetchExecutor(Executors.newSingleThreadExecutor())
.build()
return livePagedList
}
但它不起作用。我有一个错误:
java.lang.IllegalArgumentException: AsyncPagedListDiffer cannot handle both contiguous and non-contiguous lists.
我的问题是我可以为多个/不同的 LiveData 使用一个回收器视图和一个适配器吗?当我有一个回收器并且我需要将它用于最近的项目或搜索时,我的任务的最佳解决方案是什么?
解决方案
此错误的原因是因为您要求AsyncPagedListDiffer
班级比较两个不同构造的列表。
在创建recentPhotos
时,您使用PagedList.Config
. 但是,在您的searchPhotos
函数中,您LiveData<PagedList>
仅使用页面大小来构造。分页库必须比较这两个列表。使用您的配置,它们无法进行比较。
我建议您以类似的方式使用构造列表,或者使用PagedList.Config
对象或仅使用页面大小。
推荐阅读
- c# - Outlook插件如何检测电子邮件何时被删除
- angular - 在角度获取中:ReferenceError:未定义异步
- apache - 在 htaccess 上为 webp 更改 png|jpeg
- django - My get_context_data doesn't pass context to HTML properly when using Ajax
- java - 如何并排打印一副卡片?
- python - BeautifulSoup:如何提取
- 一个内的信息
- flutter - Flutter:在子小部件的状态上调用函数
- c# - ActionFilterAttribute 内的 aspnet core mvc 访问依赖指示服务
- machine-learning - 您如何区分与神经网络中的权重相关的误差?
- ios - 从 API 传递的图像未在页面浏览容器中快速显示