Created
August 14, 2020 05:01
-
-
Save Garyteck/aca68447bd8e7c0c655ff9db9ecaa529 to your computer and use it in GitHub Desktop.
Pager With RemoteMediator
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
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