英文:
Collect multiple Flux into one
问题
以下是您的代码部分翻译结果:
我想将多个 Flux 结果收集到我的 Spring Boot 服务中。我的方法:
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); //也许可以这样做???
            });
return result;
}
如何实现这个目标呢?
英文:
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?
答案1
得分: 3
你应该将你的列表放入一个Flux中,然后在其上使用flatMap,并获取每个新的Flux。flatMap将自动将所有内容“展平”为一个单独的Flux。
以下示例应该展示了这个概念:
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");
}
英文:
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");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论