事实上,我正在尝试从分页2迁移到分页3。我已经在我的代码库中用RxpagingSource成功地实现了分页2的PageKeyedDataSource。但是当我尝试实现分页2到分页库3的ItemKeyedDataSource时,我对实现它感到困惑。我还试着编写代码。但是被卡住了。这是我的代码。
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)
}
}
事实上,以前我在分页2中使用了'currentJodId‘来区分列表。但是在分页3中,我没有得到任何解决这些问题的线索。
发布于 2020-09-13 15:18:24
经过大量的搜索,我解决了这个问题。下面是更新后的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)
}
}
https://stackoverflow.com/questions/63609693
复制相似问题