Skip to content

Instantly share code, notes, and snippets.

@orcchg
Last active October 21, 2023 10:05
Show Gist options
  • Save orcchg/7d196af30b52487855831dcc131e4e49 to your computer and use it in GitHub Desktop.
Save orcchg/7d196af30b52487855831dcc131e4e49 to your computer and use it in GitHub Desktop.
Check existing access token for expiration and refresh if need
suspend fun obtainAccessToken(): String {
val accessToken = readAccessTokenFromStorageOrMemory() // might be a suspending call
if (accessToken != null && System.currentTimeMillis() < accessToken.createdAt + accessToken.expiresIn) {
return 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 newAccessToken.toString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment