Created
October 21, 2023 10:12
-
-
Save orcchg/a4659e6c506e0fe57fafb51f13a44640 to your computer and use it in GitHub Desktop.
Wrap token obtain and refresh logic in a critical section
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
suspend fun obtainAccessToken(): String = | |
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