【问题标题】:How to use PagedListAdapter with multiple LiveData(s)如何将 PagedListAdapter 与多个 LiveData 一起使用
【发布时间】:2018-07-05 16:06:24
【问题描述】:

我有一个带有 PagedListAdapter 的回收站视图。

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

【问题讨论】:

  • 我还在寻找解决方案...
  • 看起来您的 recentPhotosDataSource 来自 Room db。我说的对吗?

标签: android kotlin android-recyclerview android-livedata android-paging


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    看起来您的 recentPhotosDataSource 来自 Room db。我对吗? Room db 创建TiledPagedList,但扩展PageKeyedDataSource(或其他数据源)的SearchPhotosDataSourceFactory 创建ContiguousPagedList。这就是您收到此错误的原因。

    所以我想解决方案是创建一个新的列表适配器来显示搜索结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 2018-05-23
      • 1970-01-01
      • 2011-05-21
      • 2019-07-16
      • 2018-05-04
      相关资源
      最近更新 更多