Search code examples
fluxspring-reactive

Spring Reactive Programming: How to create a dynamic list of Publishers as input to Flux.merge


I'm new to Spring Reactive programming and I'm developing a REST endpoint that returns a Flux. For example:

 @PostMapping
 public Flux<MyResponse> processRequests(@RequestBody List<MyRequest> requests) {

        return Flux.merge(Arrays.asList(dataSource.processRequest(requests.get(0)), dataSource2.processRequest(requests.get(0)))).parallel()
                    .runOn(Schedulers.elastic()).sequential();
}

Each data souce (dataSource and dataSource2) in the example code implements an interface that looks like this:

public interface MyResponseAdapter {
    Flux<MyResponse> processRequest(MyRequest request);
}

This code works fine in that it returns the Flux as expected, but as you can see, the code only references the first element in the list of MyRequest. What I need to do is construct the Flux.merge for each element in the list of MyRequest. Can anyone point my in the right direction?


Solution

  • I think I've identified a simple solution:

            List<Flux<MyResponse>> results = new ArrayList<>();
            for (MyRequest myRequest : requests ) {
                results.add(dataSource.processRequest(myRequest));
                results.add(dataSource2.processRequest(myRequest));
            }
    
            return Flux.merge(results).parallel().runOn(Schedulers.elastic()).sequential();