I am having issues regarding pagination and saving results into remoteMediator
I need to save nextPageToken into database as
abstract fun pagingPopularItems(): PagingSource<String, PopularItemEntity>
but I cannot because Room :
error: For now, Room only supports PagingSource with Key of type Int.
Is there a way to save nextPageToken into Int or a way around it? Currently RemoteMediator only displays two API calls
@OptIn(ExperimentalPagingApi::class)
class PopularRemoteMediator @Inject constructor(
private val popularDataSource: PopularDataSource,
private val popularDataStorage: PopularDataStorage,
private val sharedPreferencesManager: SharedPreferencesManager
) : RemoteMediator<Int, PopularItemDTO>() {
override suspend fun load(
loadType: LoadType,
state: PagingState<Int, PopularItemDTO>
): MediatorResult {
return try {
val nextPageToken = sharedPreferencesManager.getString(Setting.NEXT_PAGE_TOKEN) ?: EMPTY_STRING
val loadKey: Int = when (loadType) {
LoadType.REFRESH -> 1
LoadType.PREPEND -> return MediatorResult.Success(
endOfPaginationReached = true
)
LoadType.APPEND -> {
val lastItem = state.lastItemOrNull()
if (lastItem == null) {
1
} else {
(lastItem.databaseId / state.config.pageSize) + 1
}
}
}
val pageToken = if (loadKey == 1) EMPTY_STRING else nextPageToken
val popularResponse = popularDataSource.getPopularVideos(
regionCode = "US",
pageToken = pageToken
)
sharedPreferencesManager.setString(
Setting.NEXT_PAGE_TOKEN,
popularResponse.data!!.nextPageToken ?: EMPTY_STRING
)
sharedPreferencesManager.setString(
Setting.PREV_PAGE_TOKEN,
popularResponse.data!!.prevPageToken ?: EMPTY_STRING
)
if (loadType == LoadType.REFRESH) {
popularDataStorage.clearPopulars()
}
popularDataStorage.upsertPopular(popularResponse.data)
MediatorResult.Success(
endOfPaginationReached = popularResponse.data!!.items!!.isEmpty()
)
} catch (e: IOException) {
MediatorResult.Error(e)
} catch (e: HttpException) {
MediatorResult.Error(e)
}
}
}