Last active
October 21, 2023 10:05
-
-
Save orcchg/7d196af30b52487855831dcc131e4e49 to your computer and use it in GitHub Desktop.
Check existing access token for expiration and refresh if need
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 { | |
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