在我的项目中,我想使用分页3。
在将页面添加到我的项目中之前,我可以从服务器获取数据并显示在我的RecyclerView中但在添加分页后,我遇到了这个问题:
在我的寻呼源类中:
class RepoPagingSource @Inject constructor(
private val repository: ApiRepository,
val context: Context) : PagingSource<Int, RepositoryResponse>() {
private lateinit var sharedPref: SharedPref
private lateinit var data : MutableList<RepositoryResponse>
private lateinit var responseCode : String
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, RepositoryResponse> {
sharedPref = SharedPref(context)
val responseData = mutableListOf<RepositoryResponse>()
return try {
val currentPage = params.key ?: 1
val response = repository
.getRepositories("bearer ${sharedPref.accessToken}", currentPage)
.applyIoScheduler()
.subscribe { response ->
responseCode=response.code().toString()
data = response.body()!!
Log.d("RepoPagingSource",responseCode)
Log.d("RepoPagingSource",data.size.toString())
Log.d("RepoPagingSource",data.toString())
}
responseData.addAll(data)
LoadResult.Page(
data = responseData,
prevKey = if (currentPage == 1) null else -1,
nextKey = currentPage.plus(1)
)
} catch (e: Exception) {
LoadResult.Error(e)
}
}
override fun getRefreshKey(state: PagingState<Int, RepositoryResponse>): Int? {
return null
}
}
这些日志显示了正确的数据:
Log.d("RepoPagingSource",responseCode)
Log.d("RepoPagingSource",data.size.toString())
Log.d("RepoPagingSource",data.toString())
这些日志的结果:
RepoPagingSource: 200
RepoPagingSource: 2
RepoPagingSource: [RepositoryResponse(id=5246349....
但是我的recyclerview是空的,我在调试模式下检查了代码此处:responseData.addAll(数据(数据为空!
提前感谢的帮助
我这样做了:
class RepoPagingSource @Inject constructor(
private val repository: ApiRepository,
val context: Context ) : RxPagingSource<Int, RepositoryResponse>() {
private lateinit var sharedPref: SharedPref
override fun loadSingle(params: LoadParams<Int>): Single<LoadResult<Int, RepositoryResponse>> {
sharedPref = SharedPref(context)
var nextPageNumber = params.key
if (nextPageNumber == null) {
nextPageNumber = 1
}
return repository.getRepositories("bearer ${sharedPref.accessToken}", nextPageNumber)
.subscribeOn(Schedulers.io())
.map { response: Response<MutableList<RepositoryResponse>> -> response.body()?.let { toLoadResult(it, nextPageNumber) } }
.onErrorReturn { LoadResult.Error(it) }
}
private fun toLoadResult(
response: MutableList<RepositoryResponse>,
position:Int
): LoadResult<Int, RepositoryResponse> {
return LoadResult.Page(
response,
null,
position + 1,
COUNT_UNDEFINED,
COUNT_UNDEFINED
)
}
override fun getRefreshKey(state: PagingState<Int, RepositoryResponse>): Int? {
return null
}}
在它的工作中,我还将我的版本库Rx更改为rxjava2