I have a method like below in my Spring boot app.
public Flux<Data> search(SearchRequest request) {
Flux<Data> result = searchService.search(request);//this returns Flux<Data>
Mono<List<Data>> listOfData = result.collectList();
// doThisAsync() // here I want to pass this list and run some processing on it
// the processing should happen async and the search method should return immediately.
return result;
}
//this method uses the complete List<Data> returned by above method
public void doThisAsync(List<Data> data) {
//do some processing here
}
Currently, I'm using @Async
annotated service class with doThisAsync
, but don't know how to pass the List<Data>
, because I don't want to call block
.
All I have is Mono<List<Data>>
.
My main problem is how to process this Mono separately and the search
method should return the Flux<Data>
.
Have you considered running the processing in separate threads using publishOn like in the example below? This may not be exactly what you are asking for but allows you to continue with other matters while the processing of the results in the flux is done by one or more threads, four in my example, from a dedicated scheduler (theFourThreadScheduler).
Running the example produce the following output, showing that the processing performed in doThisAsync() is performed in the background.
References: Reactor 3 Reference: Schedulers
I see two solutions for this problem:
1, Use share functionality of Flux to multicast your data
You can read more about this.
2, Handle your async funtion as a side effect
The drawback here is that you have to wait all your data to arrive on the flux and just after that you can proceed with any other processing.
3, If you'd like to avoid using
@Async
and your code is blocking