Matelutex
Matelutex

Reputation: 2220

Collect multiple Flux into one

I want to collect multiple Flux results into one in my Spring Boot service. My method:

    private Flux<VMachineResourceResponse> getDataForPhysicalMachineProtection(
          ResourcesWrapper resources, UUID groupId) {
    
        Flux<VMachineResourceResponse> result = Flux.empty();
        resources
            .getHypervResources()
            .forEach(
                resource -> {
                  Flux<VMachineResourceResponse> protectedResourcesForAgentAndId =
                      hypervAgentService.getProtectedResourcesForAgentAndId(
                          groupId, resource.getAgentId());
                  result.mergeWith(protectedResourcesForAgentAndId); //maybe that way???
                });
return result;
      }

How to do that?

Upvotes: 1

Views: 1039

Answers (1)

Toerktumlare
Toerktumlare

Reputation: 14819

You should take your list and stick it into a Flux, then flatMap over it and fetch each new Flux. The flatMap will automatically "flatten" everything into one single Flux

The following example should show the concept:

public Flux<String> getData() {

    final List<String> strings = new ArrayList<>();
    strings.add("Foo");
    strings.add("Bar");

    return Flux.fromIterable(strings)
            .flatMap(this::get);
}

private Flux<String> get(String s) {
    return Flux.just(s + "Bar", s + "Foo");
}

Upvotes: 3

Related Questions