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

标签: androidkotlinandroid-recyclerviewandroid-livedataandroid-paging

解决方案


此错误的原因是因为您要求AsyncPagedListDiffer班级比较两个不同构造的列表。

在创建recentPhotos时,您使用PagedList.Config. 但是,在您的searchPhotos函数中,您LiveData<PagedList>仅使用页面大小来构造。分页库必须比较这两个列表。使用您的配置,它们无法进行比较。

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


推荐阅读