1
votes

I have a resource API that handles an object (Product for example).

I use PUT to update this object in the database.

And I want to return just en empty Mono to the user.

There is my code :

public Mono<ServerResponse> updateProduct(ServerRequest request){
  Mono<Product> productReceived = request.bodyToMono(Product.class);
  Mono<Product> result = productReceived.flatMap(item -> {
    doSomeThing(item);
    System.out.println("Called or not called!!");
    return Mono.just(productService.product);
  }).subscribe();

  return ok()
        .contentType(APPLICATION_JSON)
        .body(Mono.empty(), Product.class);
}

The problem is my method doSomeThing() and the println are not called.

NB: I use subscribe but doesn't work.

Thanks.

1

1 Answers

2
votes

I had a similar issue when I was new to Webflux. In short, you can't call subscribe on the request body and asynchronously return a response because the subscription might not have enough time to read the body. You can see a full explanation of a similar issue here.

To make your code work, you should couple the response with your logic stream. It should be something like the following:

public Mono<ServerResponse> updateProduct(ServerRequest request){
    return request
            .bodyToMono(Product.class)
            .flatMap(item -> {
                doSomeThing(item);
                System.out.println("Called or not called!!");
                return Mono.just(productService.product);
            })
            .then(ServerResponse.ok().build());
}