0

I'm new in reactive programming and trying to wrap my head around base concepts. Basically, I want to implement a logic, that would return auth token if it's still valid or requests the new one otherwise. My best take is the code like below:

public class AsyncTokenSupplier implements Supplier<Uni<Token>> {
   private Token cachedToken;

   @Override
   public Uni<Token> get() {
        if (isTokenValid(cachedToken)) {
            return Uni.createFrom().item(cachedToken);
        } else {
            return doGetToken().onItem().invoke(token -> {
                cachedToken = token;
            });
        }
    }

   private Uni<Token> doGetToken() {
      //Api call here
   }

   private boolean isTokenValid(Token token) {
      if (token == null) {
         return false;
      }
      //Expiration check here
   }
}

The problem with this code is that it doesn't look like a thread safe - if a few threads execute "get()" method in parallel, it could end up in a few new tokens requested at the same time. I'd appreciate any guidance and recommendations.

geoand
  • 60,071
  • 24
  • 172
  • 190
Evgeny
  • 1,413
  • 2
  • 12
  • 16

1 Answers1

2

What you have here is a thread safety problem that's relatively classic. You might consider an AtomicReference to hold the token field.

That being said Uni has a memoize() operator that might just do what you want. You should be able to do something like:

return doGetToken().memoize().until(() -> someExpirationLogic());
jponge
  • 510
  • 2
  • 4