gpt4 book ai didi

android - 如何将 PagedListAdapter 与多个 LiveData 一起使用

转载 作者:行者123 更新时间:2023-11-29 01:00:57 26 4
gpt4 key购买 nike

我有一个带有 PagedListAdapter 的回收站 View 。

onCreate 我有这段代码:

 viewModel.recentPhotos.observe(this, Observer<PagedList<Photo>> {
photoAdapter.submitList(it)
})

recentPhotos 以这种方式初始化:

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 使用一个回收器 View 和一个适配器吗?当我有一个回收站并且我需要将其用于最近的项目或搜索时,什么是我的任务的最佳解决方案?

最佳答案

这个错误的原因是因为你问的是AsyncPagedListDiffer类来比较两个不同构造的列表。

在创造recentPhotos , 你使用 PagedList.Config .然而,在你的 searchPhotos函数,你构造LiveData<PagedList>仅使用页面大小。分页库必须比较这两个列表。用你的配置,它们无法比较。

我建议您以类似的方式构建列表,或者使用 PagedList.Config对象或只是一个页面大小。

关于android - 如何将 PagedListAdapter 与多个 LiveData 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51195789/

26 4 0