0
votes

I have a class where token is the instance variable of it. I'm using Spring 5-reactive, Java 8 and SpringBoot2. I'm making a call to token service and get the Mono and I'm passing the property (accessToken) of Mono into another method called getToken() using map and trying to set into this instance variable 'token'. When I log the value of this instance variable as below :-

logger.info("Verifying Token: "+ token);

I'm getting null. I believe this logging statement is getting executed first before my method call to getToken() due to async-reactive programming. Please assist me to set this property first into this instance variable before rest of the statement calls as I'm new to reactive programming and still learning it.

private String token;

  public ExchangeFilterFunction getNewExchangeFilter(Tuple2 <String, WebClient> serviceConnectionDetails,
      MultiValueMap <String, String> queryParams) {

    logger.info("Calling auth server to get new access token..................");
    Mono<AccessToken> accessToken =  commerceAccessTokenService.getUserAccessToken(serviceConnectionDetails, queryParams);
    accessToken.map(token -> getToken(token.getAccessToken()));

    logger.info("Verifying Token: "+ token);
    return (clientRequest, exchangeFunction) -> exchangeFunction.exchange(ClientRequest.from(clientRequest)
        .header("Authorization", "Bearer " + token)
        .build());

  }

  private Mono<AccessToken> getToken(String token){

    logger.info("Get Token: "+ token);
    this.token = token;
    return Mono.empty();

  }
1
getToken is a very misleading name for a method which sets the token... - Holger

1 Answers

0
votes

Mono.map applies at the time token is emitted in future. Looking at your code it doesn't make sense to proceed further should you not have this token.

My advice is to use the following code

accessToken.blockOptional().ifPresent(this::setToken); // if you have setToken defined

blockOptional() forces your code to wait for token's availability before proceeding further.