I wonder how Spring webflux works behind the scene to return value in API. Say for example in the following simple hello world API getting from the spring website (https://spring.io/guides/gs/reactive-rest-service/).
Calling the url "http://localhost:8080/hello" from browser can return the hello result.
@Component
public class GreetingHandler {
public Mono<ServerResponse> hello(ServerRequest request) {
return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
.body(BodyInserters.fromValue("Hello, Spring!"));
}
}
@Configuration
public class GreetingRouter {
@Bean
public RouterFunction<ServerResponse> route(GreetingHandler greetingHandler) {
return RouterFunctions
.route(RequestPredicates.GET("/hello").and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), greetingHandler::hello);
}
}
In the "GreetingHandler", the returned data type is "Mono", which, in my understanding, is a type of observable (or publisher) which can emit either zero or one item. But as it is an observable, an observer (or subscriber) will need to subscribe to it for getting the value. Yet for "GreetingHandler", why it can return value by calling the API ?
Say for this line, it won't show the hello world:
Mono.just("hello world");
But for this line, it will print the hello world since there is a subscriber subscribing to it.
Mono.just("hello world")
.subscribe(value -> System.out.println(value));
Is that the Spring Webflux framework has somehow do the work of automatically subscribing to it when the API is getting called, or my understanding is not correct?