Android Paging (3) 一次性加载所有页面 [英] Android Paging (3) load all pages at once
问题描述
我在我的项目中使用 Android Paging 3 库,以便逐页加载我的数据.在这个项目中,我没有使用数据库,这意味着我使用的是仅网络请求
.问题是它不是根据用户滚动加载页面,而是首先加载所有页面.这是我用于项目分页部分的代码:
I'm using the Android Paging 3 library in my project in order to load my data page by page. In this project, I'm not using database which means I'm using network only requests
. The problem is that instead of loading pages based on the user scroll, it loads all pages at first. here is the code I'm using for the paging part of my project:
我的 RxPagingSource 类:
My RxPagingSource class:
class ReviewPagingSource constructor(
private val network: Network,
private val filter: ReviewFilter,
private val config: Config,
private val cacheFirstResponse: Boolean
) : RxPagingSource<Int, Review>() {
override fun loadSingle(params: LoadParams<Int>): Single<LoadResult<Int, Review>> {
return network.getReviews(
filter.copy(page = (params.key ?: 0) , pageSize = params.loadSize),
config,
cacheFirstResponse
)
.subscribeOn(Schedulers.io())
.map { toLoadResultPage(it, params) }
.onErrorResumeNext {
when (it) {
is TimeoutException,
is NoInternetException, is NetworkException, is UnexpectedResponseException -> Single.just(
LoadResult.Error(it)
)
else -> Single.error(it)
}
}
}
private fun toLoadResultPage(
response: DataResponse<Review>,
params: LoadParams<Int>
): LoadResult<Int, Review> {
val page = params.key ?: 0
return LoadResult.Page(
response.results!!,
if (page <= 0) null else page - 1,
if (response.count ?: response.results?.count() ?: 0 < params.loadSize) null else page + 1,
LoadResult.Page.COUNT_UNDEFINED,
LoadResult.Page.COUNT_UNDEFINED
)
}
override fun getRefreshKey(state: PagingState<Int, Review>): Int? {
return state.anchorPosition?.let { state.closestPageToPosition(it) }?.nextKey
}
}
我的寻呼机是:
Pager(PagingConfig(pageSize = 5, initialLoadSize = 5,))
{ ReviewPagingSource(network, filter, config, true) }
.flow.cachedIn(viewModelScope)
相关 Gradle 部分:
Related Gradle Part:
implementation "androidx.paging:paging-runtime-ktx:3.0.0-alpha13"
implementation "androidx.paging:paging-rxjava3:3.0.0-alpha13"
任何帮助将不胜感激.
推荐答案
就我而言,这个 recipeId
数据类型很长,但是当我将其更改为字符串时,它工作正常.然后,代替 NestedScrollView
使用 SmartNestedScrollview
In my case, this recipeId
data type was long, but when I changed it to string it works fine. Then, instead of NestedScrollView
use SmartNestedScrollview
@Entity(tableName = "table_recipe")
data class RecipeList(
@PrimaryKey
@field:SerializedName("recipe_id") var recipeId : String,
@field:SerializedName("title") var title: String? = null,
)
这篇关于Android Paging (3) 一次性加载所有页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!