Sobes.tech
Junior — Middle

How to implement a blocking call in a reactive application based on WebFlux?

sobes.tech AI

Answer from AI

In a reactive application based on Spring WebFlux, blocking calls should be executed outside the reactive stream to avoid blocking the event loop and degrading performance. To do this, you can use the subscribeOn method with a dedicated Scheduler, such as Schedulers.boundedElastic(), which is designed for blocking operations.

Example:

Mono<String> blockingCall = Mono.fromCallable(() -> {
    // blocking operation, e.g., a call to a database or external service
    Thread.sleep(1000);
    return "result";
}).subscribeOn(Schedulers.boundedElastic());

blockingCall.subscribe(result -> System.out.println("Received: " + result));

Thus, the blocking code runs in a separate thread, not blocking the main reactive thread.

How to implement a blocking call in a reactive… - sobes.tech