How to add conditions in a reactive WebFlux .filter() flow in Spring?

Viewed 979

I want to create a conditional WebFilter that executes one logic if ServerWebExchangeMatcher matches, and another logic if it does not match.

The following already works for a "positive" match, by using .filter(..::isMatch). But how could I add a .orElse() method here into the flow?

class PathFilter implements org.springframework.web.server.WebFilter {
    private ServerWebExchangeMatcher paths;
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        //TODO how to add a "no-match" execution?
        return this.paths.matches(exchange)
                    .filter(ServerWebExchangeMatcher.MatchResult::isMatch)
                    .flatMap(...)
                    .then();
    }
}
1 Answers

So what @123 probably means is the following:

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    return this.paths.matches(exchange)
                .flatMap((matchResult) ->
                        matchResult.isMatch()
                                ? customLogic(exchange, chain)
                                : chain.filter(exchange)) //continue normal flow
                .then();
}

Which works, but I'd still be interested if there is a possibility to delegate a "negative-match" outcome directly inside the flow, maybe with switchIfEmpty() or similar.

Related