Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save orcchg/a4659e6c506e0fe57fafb51f13a44640 to your computer and use it in GitHub Desktop.
Save orcchg/a4659e6c506e0fe57fafb51f13a44640 to your computer and use it in GitHub Desktop.
Wrap token obtain and refresh logic in a critical section
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