【问题标题】:Collect multiple Flux into one将多个通量合二为一
【发布时间】:2020-12-08 20:16:03
【问题描述】:

我想在我的 Spring Boot 服务中将多个 Flux 结果收集到一个中。我的方法:

    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;
      }

怎么做?

【问题讨论】:

    标签: java spring-boot reactive-programming spring-webflux


    【解决方案1】:

    您应该将您的列表粘贴到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");
    }
    

    【讨论】:

    • -是的!这么简单:)
    猜你喜欢
    • 2019-11-06
    • 2023-03-20
    • 1970-01-01
    • 2019-09-30
    • 2016-03-18
    • 2010-12-15
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多