From 21264d8ff759effed92db416deb3bbbccb9f3466 Mon Sep 17 00:00:00 2001 From: FatttSnake Date: Sun, 18 Aug 2024 14:45:07 +0800 Subject: [PATCH] Refactor(ToolStorePagingSource): Optimize page key --- .../toolbox/network/paging/ToolStorePagingSource.kt | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/app/src/main/kotlin/top/fatweb/oxygen/toolbox/network/paging/ToolStorePagingSource.kt b/app/src/main/kotlin/top/fatweb/oxygen/toolbox/network/paging/ToolStorePagingSource.kt index 371274f..91fc69d 100644 --- a/app/src/main/kotlin/top/fatweb/oxygen/toolbox/network/paging/ToolStorePagingSource.kt +++ b/app/src/main/kotlin/top/fatweb/oxygen/toolbox/network/paging/ToolStorePagingSource.kt @@ -14,7 +14,11 @@ internal class ToolStorePagingSource( private val toolDao: ToolDao, private val searchValue: String ) : PagingSource() { - override fun getRefreshKey(state: PagingState): Int? = null + override fun getRefreshKey(state: PagingState): Int? = + state.anchorPosition?.let { + val anchorPage = state.closestPageToPosition(it) + anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1) + } override suspend fun load(params: LoadParams): LoadResult { return try { @@ -26,7 +30,6 @@ internal class ToolStorePagingSource( } val (_, pages, _, _, records) = data!! - val nextPage = if (currentPage < pages) currentPage + 1 else null LoadResult.Page( data = records.map(ToolVo::asExternalModel).map { toolEntity -> toolDao.selectToolByUsernameAndToolId( @@ -42,8 +45,8 @@ internal class ToolStorePagingSource( } } ?: toolEntity }, - prevKey = null, - nextKey = nextPage + prevKey = if (currentPage == 0) null else currentPage - 1, + nextKey = if (currentPage < pages) currentPage + 1 else null ) } catch (e: Throwable) { LoadResult.Error(e)