Created
October 21, 2023 18:04
-
-
Save orcchg/5d9eb64b277bd64526e2c16940c677e0 to your computer and use it in GitHub Desktop.
Run obtain and refresh token login in a single thread
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
fun obtainAccessToken(): String { | |
val kCriticalSection = DI.get<KCriticalSection>(qualifier = "shared") | |
val singleThread = DI.get<CoroutineDispatcher>(qualifier = "shared") | |
return runBlocking(singleThread) { | |
kCriticalSection.synchronized { | |
val accessToken = readAccessTokenFromStorageOrMemory() // might be a suspending call | |
if (accessToken != null && System.currentTimeMillis() < accessToken.createdAt + accessToken.expiresIn) { | |
return@synchronized accessToken.toString() // access token is valid | |
} | |
val refreshToken = readRefreshTokenFromSecureStorage() // normally a suspending call | |
// normally suspending as it makes another API call | |
val newAccessToken = performTokenRefresh( | |
accessToken = accessToken, | |
refreshToken = refreshToken | |
) | |
saveAccessTokenToStorageOrMemory(newAccessToken) // might be a suspending call | |
return@synchronized newAccessToken.toString() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment