0

I'm trying to learn reactive programming by having a non-blocking rest API. I was expecting it to reply to me immediately and do the service invocation in the background. But I could see that it is waiting for the service response and does not return the acknowledgment response object.

@PostMapping("/postflow/{incidentNumber}")
    public Mono<ResponseEntity<AcknowledgeResponse>> acknowledgeFlow(@PathVariable String number,
                                                                         @RequestHeader("correlationId") String correlationId) {
        return handler.handlePostFlow(number, correlationId)
                .thenReturn(ResponseEntity.ok().body(
                        AcknowledgeResponse.builder().status(HttpStatus.OK.value()).build()));
    }

Handler code-

public Mono<ServiceResponse> handlePostFlow(String number, String correlationId) {
        return service.getDetails(number, correlationId)
                .onErrorMap(throwable -> new RuntimeException("Something went wrong", throwable))
                .switchIfEmpty(Mono.error(new RuntimeException(" Empty response from the service ")))
                .filter(this::isServiceResultValid)
                .switchIfEmpty(Mono.error(new RuntimeException("Invalid response from the service")))
                .map(serviceResponse -> serviceResponse);
    }

AcknowledgeResponse class structure-

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class AcknowledgeResponse {

    private Integer status;
    @Builder.Default
    private Object data = "Acknowledged";
}

Can someone assist me in understanding what is wrong here? TIA.

Dan
  • 3,647
  • 5
  • 20
  • 26
Swapnil
  • 801
  • 3
  • 19
  • 42
  • 1
    I've never used continuations in this context, but isn't the whole point of `then` functions to "await" some return value, and "then" do the next step? Asynchronous programming is not about entering the store's front door before you park; it's about allowing other cars to park while you are parking. – Robert Harvey May 27 '22 at 13:38
  • I agree. I could not find any other way of returning something to the user and doing expected thing in the background. – Swapnil May 27 '22 at 13:42
  • What does Spring webflux say about this? Normally, the right thing to do is the thing that most naturally fits the gestalt of the tool you're using. – Robert Harvey May 27 '22 at 13:48
  • Reactive programming is not about doing something in background. I would suggest reading documentation first. https://spring.io/blog/2019/03/06/flight-of-the-flux-1-assembly-vs-subscription could be a good starting point to understand the difference between assembly and subscription time. – Alex May 27 '22 at 15:12
  • Sure. I'll read that. Any idea what's wrong with my code? – Swapnil May 27 '22 at 15:14
  • This might help: https://stackoverflow.com/a/57569541/6051176 – Martin Tarjányi May 28 '22 at 13:37

0 Answers0