Mixing sync and async flows (ex: refreshing oauth2 token only when necessary)

209
0
05-09-2022 06:47 AM
MTrcek
by
New Contributor II

Occasionally, I run into situations where I may or may not need an async call. In javascript, I could wrap the synchronous result in a resolved promise and continue with.then() either way. I'm curious if something like this is possible in Android. ie:

ListenableFuture<String> getRefreshedAccessToken(OAuthTokenCredential cred){
  if (cred.getExpiration().compareTo(Calendar.getInstance)<0) {
    return cred.refreshTokenAsync();
  }
  else {
    ListenableFuture<String> dummyFuture = somehowMakeAFinishedListenableFuture();
    dummyFuture.somehowSetResult(cred.getAccessToken());
    return dummyFuture;
  }
}

Our app currently uses a different authentication system, but we're adding OAuth as an option, which suddenly adds a possible refreshTokenAsync call to a lot of places. It's probably best to just restructure the code to avoid mixing sync and async flows, but regardless, I'm curious if it's possible to just treat it as async either way.

0 Kudos
0 Replies