簡體   English   中英

如何將 PagedListAdapter 與多個 LiveData(s) 一起使用

[英]How to use PagedListAdapter with multiple LiveData(s)

我有一個帶有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對象,要么僅使用頁面大小。

看起來您的recentPhotosDataSource數據源來自 Room db。 我對嗎? 客房DB創建TiledPagedList但你SearchPhotosDataSourceFactory延伸PageKeyedDataSource (或其他數據源)創建ContiguousPagedList 這就是您收到此錯誤的原因。

所以我想解決方案是創建一個新的列表適配器來顯示搜索結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM