1

我已经按照代码实验室在我的应用程序中实现了 Paging 3,并通过以下方式添加了一个带有重试按钮的页脚withLoadStateHeaderAndFooter

recycler_view_results.adapter = adapter.withLoadStateHeaderAndFooter(
    header = UnsplashLoadStateAdapter { adapter.retry() },
    footer = UnsplashLoadStateAdapter { adapter.retry() }
)

当我单击页脚 ViewHolder 中的重试按钮时,adapter.retry()确实调用了,所以那里的设置是正确的。load但是,此方法永远不会像通常那样调用我的 PagingSource方法。

我的 PagingSource (我检查了LoadResult.Error在错误情况下是否正确返回):

class UnsplashPagingSource(
    private val unsplashApi: UnsplashApi,
    private val query: String
) : PagingSource<Int, UnsplashPhoto>() {
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, UnsplashPhoto> {
        val position = params.key ?: UNSPLASH_STARTING_PAGE_INDEX
        return try {
            val response = unsplashApi.searchPhotos(query, position, params.loadSize)
            val photos = response.results
            LoadResult.Page(
                data = photos,
                prevKey = if (position == UNSPLASH_STARTING_PAGE_INDEX) null else position - 1,
                nextKey = if (photos.isEmpty()) null else position + 1
            )
        } catch (exception: IOException) {
            return LoadResult.Error(exception)
        } catch (exception: HttpException) {
            return LoadResult.Error(exception)
        }
    }
}

我的存储库:

class UnsplashRepository @Inject constructor(private val unsplashApi: UnsplashApi) {

    fun getSearchResultStream(query: String): Flow<PagingData<UnsplashPhoto>> {
        return Pager(
            config = PagingConfig(
                pageSize = NETWORK_PAGE_SIZE,
                enablePlaceholders = false
            ),
            pagingSourceFactory = { UnsplashPagingSource(unsplashApi, query) }
        ).flow
    }

    companion object {
        private const val NETWORK_PAGE_SIZE = 20
    }
}

在我的片段中,我这样做:

private fun searchPhotos(query: String) {
    searchJob?.cancel()
    searchJob = lifecycleScope.launch {
        viewModel.searchPhotos(query).collectLatest {
            adapter.submitData(it)
        }
    }
}

有趣的是,空列表的重试按钮有效:

retry_button.setOnClickListener {
    adapter.retry()
    // this works
}
4

1 回答 1

1

在我将分页依赖项从“3.0.0-alpha02”更新为“3.0.0-alpha03”后,它现在可以工作了。看起来这是图书馆中的一个错误。

后来我也找到了相应的bug报告:https ://issuetracker.google.com/issues/160194384

于 2020-08-13T09:09:01.347 回答