将多个Flux收集成一个

huangapple go评论59阅读模式
英文:

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&lt;VMachineResourceResponse&gt; getDataForPhysicalMachineProtection(
          ResourcesWrapper resources, UUID groupId) {
    
        Flux&lt;VMachineResourceResponse&gt; result = Flux.empty();
        resources
            .getHypervResources()
            .forEach(
                resource -&gt; {
                  Flux&lt;VMachineResourceResponse&gt; protectedResourcesForAgentAndId =
                      hypervAgentService.getProtectedResourcesForAgentAndId(
                          groupId, resource.getAgentId());
                  result.mergeWith(protectedResourcesForAgentAndId); //maybe that way???
                });
return result;
      }

How to do that?

答案1

得分: 3

你应该将你的列表放入一个Flux中,然后在其上使用flatMap,并获取每个新的FluxflatMap将自动将所有内容“展平”为一个单独的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&lt;String&gt; getData() {

    final List&lt;String&gt; strings = new ArrayList&lt;&gt;();
    strings.add(&quot;Foo&quot;);
    strings.add(&quot;Bar&quot;);

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

private Flux&lt;String&gt; get(String s) {
    return Flux.just(s + &quot;Bar&quot;, s + &quot;Foo&quot;);
}

huangapple
  • 本文由 发表于 2020年8月19日 22:19:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63489050.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定