Created
August 2, 2021 22:53
-
-
Save SamueldaCostaAraujoNunes/0f514dc666ab59c4c207005c632c6f12 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
@ExperimentalPagingApi | |
class CharacterRemoteMediador ( | |
private val name: String, | |
private val dao: CharacterDao, | |
private val service: CharacterService | |
) : RemoteMediator<Int, java.lang.Character>() { | |
override suspend fun load( | |
loadType: LoadType, | |
state: PagingState<Int, java.lang.Character> | |
): MediatorResult { | |
val pageSize = state.config.pageSize | |
val page = when (loadType) { | |
// Passe null para carregar a primeira pagina | |
LoadType.REFRESH -> null | |
// Já que REFRESH sempre carregará a primeira página da lista. Retorne imediatamente, informando o fim da paginação. | |
LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true) | |
//Devemos verificar explicitamente se o último item é `null` ao anexar, | |
// uma vez que passar null para networkService é válido apenas para o | |
// carregamento inicial. Se lastItem for `null`, significa que nenhum item | |
// foi carregado após o REFRESH inicial e que não há mais itens para carregar. | |
LoadType.APPEND -> { | |
val lastItem = state.lastItemOrNull() | |
?: return MediatorResult.Success( | |
endOfPaginationReached = true | |
) | |
(lastItem.id / pageSize) + 1 | |
} | |
} | |
return try { | |
val response = service.getAllCharacters( | |
page = page, | |
name = name | |
) | |
dao.insertAll(response.results) | |
MediatorResult.Success( | |
endOfPaginationReached = response.info.next == null | |
) | |
} catch (e: HttpException) { | |
Timber.d(e, "Error during fetch") | |
MediatorResult.Error(e) | |
} catch (e: IOException) { | |
Timber.d(e, "Error during fetch") | |
MediatorResult.Error(e) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment