0

实际上,我正在尝试从分页 2 迁移到分页 3。我已经在我的代码库中使用 RxpagingSource 成功实现了分页 2 的 PageKeyedDataSource。但是当我尝试将 Paging 2 的 ItemKeyedDataSource 实现到 Paging library 3 时,我对实现它感到困惑。我也尝试过编码。但卡住了。这是我的代码。

JobSliderRestApi.kt

@GET("job/list/slides")
fun getDetailOfSelectedJob(
    @Query("current_job") currentJodId: Int?,
    @Query("limit") jobLimit: Int?,
    @Query("search_in") fetchType: String?
): Single<Response<JobViewResponse>>

JobViewResponse.kt

data class JobViewResponse(
    @SerializedName("data") val data: ArrayList<JobDetail>?
) : BaseResponse()

JodSliderDataSource.kt

class JodSliderDataSource @Inject constructor(
    private val jobSliderRestApi: JobSliderRestApi,
    private val currentJobId: Int
): RxPagingSource<Int, JobDetail>() {

    override fun loadSingle(params: LoadParams<Int>): Single<LoadResult<Int, JobDetail>> {
        
        return jobSliderRestApi.getDetailOfSelectedJob(currentJobId, 20, "next").toSingle()
            .subscribeOn(Schedulers.io())
            .map { jobResponse -> jobResponse.data }
            .map { jobData -> toLoadResult(jobData, position) } // Don't know what to do
            .onErrorReturn { LoadResult.Error(it) }
    }

    //Don't know what to do
    private fun toLoadResult(data: JobDetail, position: Int): LoadResult<Int, JobDetail> {
        /**val prevKey = if (position == 1) null else position-1
        val nextKey = if (data.hasMore) position+1 else null

        return LoadResult.Page(data.jobs, prevKey, nextKey)*/
    }

    @ExperimentalPagingApi
    override fun getRefreshKey(state: PagingState<Int, JobDetail>): Int? {
        return super.getRefreshKey(state)
    }
}

事实上,以前我使用“currentJodId”来区分第 2 页中的列表。但是在第 3 页中,我没有得到任何解决这些问题的线索

4

1 回答 1

0

经过大量搜索,我解决了问题。这是更新后的 JodSliderDataSource 类

class JodSliderDataSource @Inject constructor(
    private val jobSliderRestApi: JobSliderRestApi
): RxPagingSource<Int, JobDetail>() {

    override val keyReuseSupported = true

    @ExperimentalPagingApi
    override fun getRefreshKey(state: PagingState<Int, JobDetail>): Int? {
        return state.anchorPosition?.let {
            state.closestItemToPosition(it)?.jobId
        }
    }

    override fun loadSingle(params: LoadParams<Int>): Single<LoadResult<Int, JobDetail>> {
        return jobSliderRestApi.getDetailOfSelectedJob(42673, 2, "next").toSingle()
            .subscribeOn(Schedulers.io())
            .map { jobResponse -> toLoadResult(jobResponse.data) }
            .onErrorReturn { LoadResult.Error(it) }
    }

    private fun toLoadResult(data: ArrayList<JobDetail>): LoadResult<Int, JobDetail> {
        return LoadResult.Page(data = data, prevKey = null, nextKey = data.lastOrNull()?.jobId)
    }
}
于 2020-09-13T07:18:23.663 回答