Skip to content

Instantly share code, notes, and snippets.

@smarteist
Last active October 9, 2024 09:55
Show Gist options
  • Save smarteist/bd69149f92709c60e6fd0b7d172f7b0b to your computer and use it in GitHub Desktop.
Save smarteist/bd69149f92709c60e6fd0b7d172f7b0b to your computer and use it in GitHub Desktop.
Repository caching mechanisms
/**
* Cache-Aside (Lazy Loading): Read from cache and return it, then update the cache later.
*/
fun getUserConfigLazily(): Flow<UserConfig?> = flow {
emitAll(local.getUserConfigAsFlow())
if (onlineChecker.isOnline) {
val remoteConf = remote.getUserConfig()
if (remoteConf != null) {
local.updateUserConfig(remoteConf)
}
}
}
/**
* Cache-First : Read from cache; if missed, read from remote and return.
*/
fun getUserConfigCacheFirst(): Flow<UserConfig?> = flow {
val userConfig = local.getUserConfig()
if (userConfig != null) {
emit(userConfig)
} else {
emitAll(getUserConfigReadThrough())
}
}
/**
* Read-Through Cache: Read from remote and return, then update the cache.
*/
fun getUserConfigReadThrough(): Flow<UserConfig?> = flow {
if (onlineChecker.isOnline) {
val remoteConf = remote.getUserConfig()
if (remoteConf != null) {
local.updateUserConfig(remoteConf)
emit(remoteConf)
} else {
emit(null)
}
} else {
emit(null)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment