'how to skip switchIfEmpty (avoid Mono<Optional>) if flatMap returns Mono<Void>
I'm implementing a GatewayFilter, which checks the cached result first before contacting HTTP API.
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// loadFromCache may return Mono.emtpy if no cached result found
return loadFromCache(exchange.getRequest().getPath().toString())
.flatMap(s -> {
// if cached value exists, return directly
ServerHttpResponse response = exchange.getResponse();
Flux<DataBuffer> cached = Flux.just(response.bufferFactory().wrap(s.getBytes(StandardCharsets.UTF_8)));
return response.writeWith(cached);
}).switchIfEmpty(Mono.defer(() -> {
// if no cached value found, calling http api to get a response
return chain.filter(exchange);
}));
}
The problem is switchIfEmpty also works on Mono<Void> returned from flatMap operation. One solution is to map the value from loadFromCache to Optional<String>, then do ifPresent check in flatMap. This seems unnecessary to me. Is there any other solution without using Optional? Thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
