Created
March 31, 2023 08:18
-
-
Save pishen/e563e5939a0635d2785770ac7e0f1b44 to your computer and use it in GitHub Desktop.
Token Refresher with lazy Future
This file contains 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
class Token() { | |
def newToken(): Eval[Future[AccessToken]] = Eval.later(Future(???)) | |
val tokenRef: AtomicReference[Eval[Future[AccessToken]]] = AtomicReference(newToken()) | |
def get(): Future[AccessToken] = { | |
val eval = tokenRef.get() | |
eval.value.flatMap { token => | |
if (token.isExpiring) { | |
tokenRef.compareAndSet(eval, newToken()) | |
tokenRef.get().value | |
} else { | |
Future.successful(token) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment