我想使用 Android JetPack 中的分页库进行页面分页。我尝试了不同的方法,但是没有任何空白列表(空的 RecyclerView )。.
我正在使用 Dagger2 , OkHttp , Retrofit2 。 这是我的 PageKeyedPhotoDataSource :
override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, Photo>) {
networkState.postValue(NetworkState.LOADING)
initialLoad.postValue(NetworkState.LOADING)
// triggered by a refresh, we better execute sync
try {
val response = fetchPhotos(1).execute()
if (response.isSuccessful) {
val data = response.body()?.photos
val items = data?.map { it } ?: emptyList()
networkState.postValue(NetworkState.LOADED)
initialLoad.postValue(NetworkState.LOADED)
callback.onResult(items, null, 2)
} else {
initNetworkError("error code: ${response.code()}")
}
} catch (ioException: IOException) {
initNetworkError(ioException.message ?: "unknown error")
}
}
override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, Photo>) {
networkState.postValue(NetworkState.LOADING)
fetchPhotos(params.key).enqueue(
object : retrofit2.Callback<PhotoService.PhotoWrapper> {
override fun onFailure(call: Call<PhotoService.PhotoWrapper>, t: Throwable) {
networkState.postValue(NetworkState.error(t.message ?: "unknown err"))
}
override fun onResponse(
call: Call<PhotoService.PhotoWrapper>,
response: Response<PhotoService.PhotoWrapper>
) {
if (response.isSuccessful) {
val data = response.body()?.photos
val items = data?.map { it } ?: emptyList()
callback.onResult(items, params.key + 1)
networkState.postValue(NetworkState.LOADED)
} else {
networkState.postValue(
NetworkState.error("error code: ${response.code()}"))
}
}
}
)
}
PhotoDataSourceFactory:
val sourceLiveData = MutableLiveData<PageKeyedPhotoDataSource>()
override fun create(): DataSource<Int, Photo> {
val source = PageKeyedPhotoDataSource(dataSource = dataSource,
query = query)
sourceLiveData.postValue(source)
return source
}
这是照片库:
fun getMovies(query: String, pageSize: Int): Listing<Photo>
ViewModel:
val movies = switchMap(repoResult) { it.pagedList }!!
这是片段:
viewModel.movies.observe(this, Observer<PagedList<Photo>>{
adapter.submitList(it)
})
RemoteDataSource:
fun fetchPhotos(page: Int): Call<PhotoService.PhotoWrapper> {
return photoService.getPhotos(page)
}
这是我的 PhotoService :
@GET("photos")
fun getPhotos(@Query("page") page: Int = 1, @Query("per_page") per_page: Int = 15): Call<PhotoWrapper>
class PhotoWrapper(
val photos: List<Photo>
)
希望您能理解我的问题。我只想知道为什么 RecyclerView 为空。问题是我没有错误,也不知道该怎么办。