Spring Webflux HttpResponse

Viewed 336
class Test{
    public Mono<ServerResponse> test(ServerRequest req){
        Mono<String> data = Mono.just("test");
        System.out.print(data);
        return ServerResponse.ok.body(data, String.class);
    }
}

When the client makes a request, "MonoJust" is printed at line 4, but "test" is returned in the Http Response Body. I know that a publisher doesn't produce data before a subscription, so why does the Http Response contain "test" not "MonoJust"?

1 Answers

This behaviour might look a bit odd because you've just used Mono to wrap an actual value - but this is not what reactor (and reactive frameworks in general) are designed for.

Remember that Mono is a publisher which may or may not emit an element in the future, not just a wrapper for a given value. When you return ServerResponse.ok.body(), you're explicitly stating that you want the body to contain the result emitted by the publisher that you're passing in - the method then returns another publisher, Mono<ServerResponse>, that publishes the required server response when your data publisher emits a value.

System.out.print on the other hand is implicitly calling the toString() method on Mono, which needs to produce a value now, without blocking or waiting (it's returning a String after all, not a Mono<String>.) It can't print the value since it won't necessarily be there, so instead it just prints the name of its class (MonoJust in this case refers to the fact you've instantiated the Mono with Mono.just().)

Related