0

Hi I just started learning reactive programming

I have this piece of code here and my process here should be I will call tokenRepository to get the token and then, use the token.getAccessToken() to be used as a parameter on the cardRepository.findAllCards()

public class CardService {

    private final CardRepository cardRepository;
    private final TokenRepository tokenRepository;

    public CardService(CardRepositorycardRepository,
                       TokenRepository tokenRepository) {
        this.cardRepository = cardRepository;
        this.tokenRepository = tokenRepository;
    }

    public Mono<CardCollection> findAllCards(MultiValueMap<String, String> queryParams) {
        Mono<Token> token =tokenRepository.requestToken(); 

        // then I would like to use the token.getAccessToken
        return cardRepository.findAllCards(token.getAccessToken, queryParams); // Then this should return Mono<CardCollection>
    }
}

Would like to know if this is possible?

Fhrey
  • 11
  • 3

1 Answers1

1

I found the answer although I'm not quite sure if this is the correct way.

How to pass data down the reactive chain

This is what I've done with my code.

public Mono<CardCollection> findAllCards(MultiValueMap<String, String> queryParams) {
  return tokenRepository.requestToken().flatMap(token -> {
      return cardRepository.findAllCards(token.getAccessToken(), queryParams);
  });
}
Fhrey
  • 11
  • 3
  • that is correct as long as the token repository is using a non blocking database driver, or restclient (like webflux) to fetch the token. – Toerktumlare Apr 25 '20 at 10:01
  • Thanks @ThomasAndolf, are there any elegant way to do this? what if there's a large flow for this specific method? – Fhrey Apr 26 '20 at 00:39
  • that looks rather elegant already, what about if there is a large flow, do you see any problem with that? – Toerktumlare Apr 26 '20 at 01:36
  • Be aware about what if tokenRepository.requestToken() return null or empty token – Shoshi Apr 26 '20 at 02:33
  • @ThomasAndolf nothing really, I just thought there is another way to do things. Thanks for validating my answers it was truly helpful. – Fhrey Apr 26 '20 at 05:12
  • @Shoshi yes, currently looking on how to that properly thanks for the heads up :D – Fhrey Apr 26 '20 at 05:13
  • For that you should use switchifempty or defaultifempty – Shoshi Apr 26 '20 at 05:28