Why paging 3.0 load 2 page at beginning
Asked Answered
S

2

8

I'm trying to track infinite scrolling. I've implemented the tracking in pagingsource. When I open the page, paging loads 2 pages. And without even scrolling, the track request is sending. How can i stop paging from loading 2 pages ?

ExamplePagingSource: PagingSource<String, UIItem>() {

private var scrollDepth = 0

override suspend fun load(params: LoadParams<String>): LoadResult<String, UIItem> {
    val pageKey = params.key ?: ""

    return try {
        val exampleData = getExampleData()

        
        scrollDepth++
        trackScroll()
        

        LoadResult.Page(
            data = items,
            prevKey = if (isFirstPage) null else pageKey,
            nextKey = exampleData.pageKey.ifEmpty { null }
        )
    } catch (e: Exception) {
        Timber.e(e, "Error")
        LoadResult.Error(e)
    }
}

UPDATE I solved it with prefetchDistance

Spool answered 9/8, 2022 at 8:14 Comment(3)
Some code maybe?Custodial
@DarShan i added an exampleSpool
Can anyone explain why paging3 is doing this .Uncommon
S
12

I solved it with prefetchDistance. If you set prefetch distance to 2. Paging library call api at second to last item. You must set in PagingConfig

Pager(
    config = PagingConfig(
        pageSize = PAGE_SIZE,
        prefetchDistance = PREFETCH_DISTANCE
    ),
    pagingSourceFactory = ::pagingSource
)
Spool answered 9/8, 2022 at 9:24 Comment(2)
Providing the code that solved your issue might help future developers, an answer you posted currently probably wouldn't help a lotSolvable
thx i added some example and explanationSpool
D
3

In addition to Kaan answer, I have also updated the initialLoadSize

and set its value to 1. which is documented as follows:

Defines requested load size for initial load from PagingSource, typically larger than pageSize, so on first load data there's a large enough range of content loaded to cover small scrolls.

So the end result would be

    Pager(
         config = PagingConfig(
      pageSize = pageSize, prefetchDistance = 0, initialLoadSize = 1),
      remoteMediator = PageKeyedRemoteMediator(db, api, page)
    ) {
        pagingSourceFactory = ::pagingSource
    }.flow
Doubleacting answered 25/11, 2022 at 14:26 Comment(2)
Thank you @Xexolas. That's much stabil than set prefetch distance i think.Spool
if you set prefetchDistance = 0, then you need to set enablePlaceholders = true or you will get an exceptionSpanish

© 2022 - 2024 — McMap. All rights reserved.