Skip to content

Instantly share code, notes, and snippets.

@wangerekaharun
Last active September 16, 2020 15:40
Show Gist options
  • Save wangerekaharun/143bf143accf25f4bfb731aab19b0469 to your computer and use it in GitHub Desktop.
Save wangerekaharun/143bf143accf25f4bfb731aab19b0469 to your computer and use it in GitHub Desktop.
@OptIn(ExperimentalPagingApi::class)
class RedditRemoteMediator(
private val redditService: RedditService,
private val redditDatabase: RedditDatabase
) : RemoteMediator<Int, RedditPost>() {
override suspend fun load(
loadType: LoadType,
state: PagingState<Int, RedditPost>
): MediatorResult {
return try {
val loadKey = when (loadType) {
LoadType.REFRESH -> null
LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
LoadType.APPEND -> {
state.lastItemOrNull()
?: return MediatorResult.Success(endOfPaginationReached = true)
getRedditKeys()
}
}
val response = redditService.fetchPosts(
loadSize = state.config.pageSize,
after = remoteKey?.after,
before = remoteKey?.before
)
val listing = response.body()?.data
val redditPosts = listing?.children?.map { it.data }
if (redditPosts != null) {
redditDatabase.withTransaction {
redditDatabase.redditKeysDao()
.saveRedditKeys(RedditKeys(0, listing.after, listing.before))
redditDatabase.redditPostsDao().savePosts(redditPosts)
}
}
MediatorResult.Success(endOfPaginationReached = listing?.after == null)
} catch (exception: IOException) {
MediatorResult.Error(exception)
} catch (exception: HttpException) {
MediatorResult.Error(exception)
}
}
private suspend fun getRedditKeys(): RedditKeys? {
return redditDatabase.redditKeysDao().getRedditKeys().firstOrNull()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment