kotlin Android分页(3)一次加载所有页面

ljo96ir5  于 12个月前  发布在  Kotlin
关注(0)|答案(2)|浏览(139)

我在我的项目中使用Android Paging 3库,以便逐页加载数据。在这个项目中,我没有使用数据库,这意味着我使用network only requests。问题是,它不是基于用户滚动来加载页面,而是首先加载所有页面。下面是我在项目分页部分使用的代码:
我的RxPagingSource类:

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相关部分:

implementation "androidx.paging:paging-runtime-ktx:3.0.0-alpha13"
implementation "androidx.paging:paging-rxjava3:3.0.0-alpha13"

如果你能帮忙的话,我将不胜感激。

sirbozc5

sirbozc51#

在我的例子中,这个recipeId数据类型很长,但是当我将其更改为string时,它工作得很好。然后,使用SmartNestedScrollview代替NestedScrollView

@Entity(tableName = "table_recipe")
data class RecipeList(
        @PrimaryKey
        @field:SerializedName("recipe_id") var recipeId : String,
        @field:SerializedName("title") var title: String? = null,
)
4ioopgfo

4ioopgfo2#

如果您的浏览器视图具有针对高度的换行内容,请将其更改为匹配父级或0dp

相关问题