0

I imitated the codelab and implemented the getRefreshKey() method, but since the params.loadSize is 3*PAGE_SIZE after refresh(that is, to delete an item or edit an item), most of the probability of my recyclerview will not return to the original position. What should I do? This is my pagingSource:

class PasswordPagingSource2(
        val type: String,
        val service: PasswordService,
        val PAGE_SIZE:Int) :
        PagingSource<Int, Any>() {

    private  val PAGE_INDEX = 0


    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Any> {
        val page = params.key ?: PAGE_INDEX

        return try {


            val list =
                    service.getPasswords(
                    "{\"type\":\"$type\"}",
                    params.loadSize, page * PAGE_SIZE).items
            val preKey = if (page > 0) page - 1 else null
            val nextKey = if (list.isNotEmpty()) page + (params.loadSize/PAGE_SIZE)else null
            return LoadResult.Page(data =list, prevKey = preKey, nextKey = nextKey)
        } catch (exception: IOException) {
            return LoadResult.Error(Throwable("IO Error"))
        } catch (exception: HttpException) {
            return LoadResult.Error(Throwable("Network Error"))
        }

    }


    override fun getRefreshKey(state: PagingState<Int, Any>): Int? {
      
        val page = state.anchorPosition?.let { anchorPosition->
            state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)
                    ?:state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)
        }
        return page
    }


}
pnkj
  • 406
  • 5
  • 17

1 Answers1

0

It is your responsibility to ensure that initialLoadSize will load enough items to cover the viewport so that on invalidation, you will load enough items such that the previous list, and the initial refresh after invalidation overlap so that DiffUtil can help you resume scrolling position.

If you want to keep your pageSize the same, you can modify initialLoadSize in PagingConfig instead. As a rule of thumb, you want it to load at least 2x the number of visible items at once, both before and after the last PagingState.anchorPosition.

dlam
  • 3,547
  • 17
  • 20