Last active
December 19, 2022 01:10
-
-
Save chenzhang2006/0f52c87663210ad6937b60e2f1ae5877 to your computer and use it in GitHub Desktop.
Repository with in-memory cache to support concurrency
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
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