【问题标题】:Paging 3 - Why does my retry footer not call my PagingSource's load method?Paging 3 - 为什么我的重试页脚没有调用我的 PagingSource 的加载方法?
【发布时间】:2020-08-12 09:41:31
【问题描述】:

我已经按照 codelab 在我的应用中实现了 Paging 3,并通过 withLoadStateHeaderAndFooter 添加了一个带有重试按钮的页脚:

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

当我点击页脚 ViewHolder 中的重试按钮时,adapter.retry() 确实被调用了,所以那里的设置是正确的。然而,这个方法永远不会像往常一样调用我的 PagingSource 的 load 方法。

我的 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
}

【问题讨论】:

    标签: android kotlin android-paging android-paging-library android-paging-3


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-11-06
      • 2021-07-23
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      相关资源
      最近更新 更多