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.