Alcanzer
Alcanzer

Reputation: 57

Mono::then returns null

I'm relatively new to reactive programming. My question is regarding Mono::then

What I want to do is, extract the body from incoming request, set it to a static variable. Once that is done, send a response saying that the service has started. But the following code always returns "Service started for: null".

I thought Mono::then should run after the first mono completes(in this case, after setting the static variable) and return "Service started for: a,b,c".

Is my understanding wrong?

(Also, any code criticism is appreciated)

public Mono<ServerResponse> getStatus(ServerRequest req) {
        Mono<List<Request>> body = req.bodyToFlux(Request.class).collectList();
        return ServerResponse.ok()
                .body(body.doOnNext(i -> {
                    Service.a = i;
                    logger.info("Service started for : {}", i.toString());
                })


                        .then(Mono.just("Service started for: " + Service.a)), String.class);
    }

Upvotes: 0

Views: 2601

Answers (1)

Martin Tarj&#225;nyi
Martin Tarj&#225;nyi

Reputation: 9947

Communicating through static variables are very discouraged (especially in functional and reactive programming). As in your question you didn't provide enough information about the Service you start, it's a bit difficult to recommend.

However, based on the available information, I would start out with something like this:

public Mono<ServerResponse> getStatus(ServerRequest req) {
    return req.bodyToFlux(Request.class)
            .collectList()
            .doOnNext(requestBody -> System.out.println("Do your service start here in the background."))
            .flatMap(requestBody -> ServerResponse.ok().syncBody("Service started for: " + requestBody));
}

Upvotes: 1

Related Questions