Created
June 6, 2021 09:29
-
-
Save annchar/8cca521565cca93346ffdcc3f5157e23 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const val NETWORK_PAGE_SIZE = 500 | |
private const val INITIAL_LOAD_SIZE = 1 | |
class CryptoListPagingSource( | |
private val service: APIService, | |
private val mapper: CryptoListMapper | |
) : PagingSource<Int, CryptoItemResponse>() { | |
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, CryptoItemResponse> { | |
// Start refresh at position 1 if undefined. | |
val position = params.key ?: INITIAL_LOAD_SIZE | |
val offset = if (params.key != null) ((position - 1) * NETWORK_PAGE_SIZE) + 1 else INITIAL_LOAD_SIZE | |
return try { | |
val jsonResponse = service.getCryptoList(start = offset, limit = params.loadSize).data | |
val response = mapper.toCryptoListResponse(jsonResponse) | |
val nextKey = if (response.isEmpty()) { | |
null | |
} else { | |
// initial load size = 3 * NETWORK_PAGE_SIZE | |
// ensure we're not requesting duplicating items, at the 2nd request | |
position + (params.loadSize / NETWORK_PAGE_SIZE) | |
} | |
LoadResult.Page( | |
data = response, | |
prevKey = null, // Only paging forward. | |
// assume that if a full page is not loaded, that means the end of the data | |
nextKey = nextKey | |
) | |
} catch (e: Exception) { | |
LoadResult.Error(e) | |
} | |
} | |
override fun getRefreshKey(state: PagingState<Int, CryptoItemResponse>): Int? { | |
// We need to get the previous key (or next key if previous is null) of the page | |
// that was closest to the most recently accessed index. | |
// Anchor position is the most recently accessed index | |
return null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment