Skip to content

Instantly share code, notes, and snippets.

@Garyteck
Created August 14, 2020 05:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Garyteck/aca68447bd8e7c0c655ff9db9ecaa529 to your computer and use it in GitHub Desktop.
Save Garyteck/aca68447bd8e7c0c655ff9db9ecaa529 to your computer and use it in GitHub Desktop.
Pager With RemoteMediator
class Repository(val db: CryptoDatabase, val api : NetworkInterface) {
fun getCryptos() : Flow<PagingData<CryptoCurrency>> {
return Pager(
config = PagingConfig(PAGE_SIZE),
initialKey = 0,
remoteMediator = RepositoryMediator(db,api),
pagingSourceFactory = { db.cryptoDao().getCryptos() }
).flow
}
}
class RepositoryMediator(val db: CryptoDatabase, val api: NetworkInterface) : RemoteMediator<Int, CryptoCurrency>() {
override suspend fun load(loadType: LoadType, state: PagingState<Int, CryptoCurrency>): MediatorResult {
val offset : Int = when(loadType) {
LoadType.REFRESH -> 0
LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
LoadType.APPEND -> {
db.cryptoDao().getCryptoInDb()
}
}
val cryptos = api.getCryptos(limit = state.config.pageSize, offset = offset).body()?.data
db.withTransaction {
if (loadType == LoadType.REFRESH) {
db.cryptoDao().deleteAllCryptos()
}
cryptos?.let {
db.cryptoDao().insertCryptos(it)
}
}
return MediatorResult.Success( endOfPaginationReached = cryptos?.isEmpty() ?: true)
}
}
// Paging Library dependencies in build.gradle
implementation "androidx.paging:paging-runtime:3.0.0-alpha02"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment