Search code examples
spring-webfluxreactor

webfilter do subscribe in filter logic


I'm using webflux.

There's a warning from intellij idea.

warning message: calling subscribe in non-blocking scope

Is there anyway to subscribe the response mono correctly? (I don't want to affect an original request.)

@Slf4j
@Component
public class CustomWebFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        Mono<String> response = getAsyncResponse();
        mono.subscribe();

        return chain.filter(exchange);
    }
}

Solution

  • You should not subscribe() but you need to construct reactive flow and WebFlux will subscribe to it. In addition, subscribe is async operation and your filter will not work as expected.

    @Slf4j
    @Component
    public class CustomWebFilter implements WebFilter {
    
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
            return getAsyncResponse()
                    .flatMap(respone -> chain.filter(exchange));
        }
    }