Last active
October 9, 2024 09:55
-
-
Save smarteist/bd69149f92709c60e6fd0b7d172f7b0b to your computer and use it in GitHub Desktop.
Repository caching mechanisms
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
/** | |
* 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