Skip to content

Instantly share code, notes, and snippets.

@chenzhang2006
Last active December 19, 2022 01:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chenzhang2006/0f52c87663210ad6937b60e2f1ae5877 to your computer and use it in GitHub Desktop.
Save chenzhang2006/0f52c87663210ad6937b60e2f1ae5877 to your computer and use it in GitHub Desktop.
Repository with in-memory cache to support concurrency
private val lock = Mutex() // #1
private var cachedAccount: Account? = null
suspend fun getAccount(): Account? {
return cachedAccount ?: mutex.withLock { // #2, #3, #6
cachedAccount ?: withContext(Dispatchers.IO) { // #4, #5, #6
val networkModel = ... // perform network query and response parsing
cachedAccout = networkModel.mapToAccountDomain()
cachedAccount
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment