Home > OS >  Filtering and default value in Reactor
Filtering and default value in Reactor

Time:12-07

I'm presently experiencing a really strange and frustrating issue at the moment. I have some code that is being tested that runs through a reactive call chain containing a series of filtering operations.

As the test runs through the code and a 'false' value is returned, the code still passes through to the next call in the chain instead of just returning.

Since I'm still a 'reactive newbie' I'm figuring I'm probably not doing something incorrectly here in the reactive code chain.

Here is the code:

    private Mono<GetCardNumberServiceResponseData> updateCardNumberIfLastFourValidAndShaIsNull(Card card, GetCardNumberServiceResponseData responseData) {
        return Mono.just(responseData)
            .filter(response -> isValidLastFour(card, response))
            .defaultIfEmpty(responseData)
            .filter(response -> shaIsNull(card))
            .defaultIfEmpty(responseData)
            .flatMap(response -> updateCardNumber(card, response));
    } 

This is the portion that's not evaluating correctly:

.filter(response -> isValidLastFour(card, response))

This is what 'isValidLastFour' currently looks like:

    private boolean isValidLastFour(Card card, GetCardNumberServiceResponseData responseData) {
//      String cardNumberFromResponse = responseData.getCardNumber();
//      String lastFourFromResponse =
//          cardNumberFromResponse.substring(cardNumberFromResponse.length() - 4);
//      return card.getLastFour().equals(lastFourFromResponse);
        return false;
    }

So presently I just have it hard-coded to return 'false', but as I step through the test with the debugger, the execution just passes right through as if 'true' is being returned, so I'm really just at a loss at what might be causing this behavior.

As always, any and all help is always greatly appreciated!

CodePudding user response:

If you want responseData to be the default value, in case there is an empty Mono, you have to put defaultIfEmpty at the end of the chain:

 return Mono.just(responseData)
        .filter(response -> isValidLastFour(card, response))
        .filter(response -> shaIsNull(card))
        .flatMap(response -> updateCardNumber(card, response))
        .defaultIfEmpty(responseData);

Even better, you can merge those filters:

 return Mono.just(responseData)
        .filter(response -> isValidLastFour(card, response) && shaIsNull(card))
        .flatMap(response -> updateCardNumber(card, response))
        .defaultIfEmpty(responseData);
  • Related