我想实现分页以在我的应用程序中显示我想要的项目 View 的一大块列表。这就是为什么我选择使用谷歌新发布的分页库,即分页库 3。我在我的应用程序中使用 Rxjava、Livedata 和 ViewModel。
实现分页库后,我面临一个奇怪的问题。当我调用获取列表的方法时,它一次又一次地调用并且没有停止调用。事实上,虽然我没有滚动列表,但它会自动增加页码。
这是我尝试过的代码JobListRestApi.kt
interface JobListRestApi {
@GET("job/list")
fun getJobResponse(
@Query("page") pageNumber: Int
): Single<Response<JobResponse>>
}
JobListDataSource.kt
class JobListDataSource @Inject constructor(
private val jobListRestApi: JobListRestApi
): RxPagingSource<Int, Job>() {
override fun loadSingle(params: LoadParams<Int>): Single<LoadResult<Int, Job>> {
val position = params.key ?: 1
return jobListRestApi.getJobResponse(position).toSingle()
.subscribeOn(Schedulers.io())
.map { jobResponse -> jobResponse.jobData.jobs }
.map { jobs -> toLoadResult(jobs, position) }
.onErrorReturn { LoadResult.Error(it) }
}
private fun toLoadResult(data: ArrayList<Job>, position: Int): LoadResult<Int, Job> {
val prevKey = if (position == 1) null else position-1
val nextKey = if (position == data.size) null else position+1
return LoadResult.Page(data, prevKey, nextKey)
}
}
JobListRepositoryImpl.kt
class JobListRepositoryImpl @Inject constructor(
private val jobListDataSource: JobListDataSource
): JobListRepository {
override fun getJobs(): Flowable<PagingData<Job>> {
return Pager(PagingConfig(pageSize = 20)) {
jobListDataSource
}.flowable
}
}
JobListViewModel.kt
class JobListViewModel @Inject constructor(
private val jobListRepository: JobListRepository
): BaseViewModel() {
val jobs: MutableLiveData<PagingData<Job>> = MutableLiveData()
fun getJobs() {
if (jobs.value == null) {
compositeDisposable += jobListRepository.getJobs()
.subscribe({
jobs.value = it
}, {
handleException(it)
})
}
}
}
JobListFragment.kt
class JobListFragment : BaseFragment<JobListViewModel>() {
private val jobAdapter: JobAdapter by lazy {
JobAdapter { }
}
override fun getLayoutResource() = R.layout.fragment_job_list
override fun initWidget() {
job_recycler_view.adapter = jobAdapter
}
override fun onResume() {
super.onResume()
viewModel.getJobs()
}
override fun observeLiveData() {
observe(viewModel.jobs) {
jobAdapter.submitData(lifecycle, it)
}
}
}
输出日志是https://base-url/job/list?page=1
https://base-url/job/list?page=2
https://base-url/job/list?page=3
https://base-url/job/list?page=4
https://base-url/job/list?page=5
https://base-url/job/list?page=6
https://base-url/job/list?page=7
除非我转到 RecyclerView 中 block 的最后一项并滚动列表,否则如何停止调用串行 api
最佳答案
您通过返回 null
告诉 Paging 没有更多要加载的内容了。对于 prevKey
和 nextKey
在 LoadResult.Page
由于它无限附加,看起来你从未设置 nextKey
至null
.也许您打算检查 data.isEmpty()
而不是 key == data.size
?
关于android - 在 Google Paging Library 3 中没有任何滚动的情况下,Api 调用不会一次又一次地停止调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63565381/