I am trying to create framework which should return 201 response. When a request is made to an API then i want to send back response immediately and process the request in background.
Flux.fromIterable(request.getApiRequests()).log().flatMap(item -> {
WebClient.RequestHeadersSpec apiCallSpec = WebClient.create(request.getBasePath())
.method(item.getHttpMethod()).uri(item.getPath()).accept(MediaType.valueOf(item.getAccept()))
.contentType(MediaType.valueOf(item.getContentType())).body(BodyInserters.fromObject(item.getPayload()));
return apiCallSpec.retrieve().bodyToMono(String.class);
}).subscribe();
return Mono.just("Created");
I want the flux part to happen in the background but as of now API waits and responds once whole flux is streamed.
If I correctly understand what you are trying to do, I can suggest you use a different design.
Don't create a Flux in your (what I presume to be) controller above. Instead you could create an instance of a Hot Stream in your app (could be a Bean in your context) and then use that instance like this:
myHotStream.next(item);
Another component in you app can the use the same instance to subscribe to it.
Read the documentation here: http://projectreactor.io/docs/core/release/reference/#reactor.hotCold And another example here, chapter 8. Hot Streams
Edit
Just a sidenote. Usually HTTP 201 Created implies that an entity has been successfully created. If this creation happens asynchronously after you send the response, it might be better to send an HTTP 200 OK instead. You cannot guarantee that the creation was successful but you can communicate that the request has been successfully received (ex: passed validation).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With