首页 > 解决方案 > 如何以反应的方式检索和处理实体的孩子的孩子?

问题描述

A、B 和 C 是 couchbase 数据库中的一些文档,其层次结构如下:

public class A {
   ...
   private Set<B> bSet;
}
public class B {
   ...
   private Set<C> cSet;
}
public class C {
  ...
}

存储库是反应式的并返回 Flux 或 Mono。

服务“aService”与实体 A 一起工作。

public void fixme() {
        aService.findAll() // Flux<A>
                .flatMap(a-> { // flatMap called on a reactive type. The contained code is not consumed
                    a.getBSet().stream()
                            .flatMap(b -> b.getCSet().stream()) // flatMap called on Stream<B>
                            .forEach(c -> {
                                try {
                                    voidMethod(c, a);
                                } catch (E1| E2 e) {
                                    log.error("Exception occured: {}", e);
                                }
                            });
                    return Mono.empty(); // return from the flatMap called on the reactive type
                });
    }

目标:我想调用那个 voidMethod(),但正如评论中所述,在响应类型上调用的 flatMap 中包含的代码不会被调用。

voidMethod ()需要处理来自A类的一些信息和来自C类的一些信息,它的返回类型是 void。

更新:由于没有订阅者订阅通量,因此未调用 flatMap 的内容。我可以通过订阅通量来执行内部代码:

 public void fixed() {
    aService.findAll()
            .flatMap(a -> {
                a.getBSet().stream().map(B::getCSet)
                        .flatMap(Set::stream)
                        .forEach(c -> {
                            try {
                                voidMethod(c, a);
                            } catch (E1 | E2 e) {
                                // handle e
                            }
                        });
                return Mono.empty();
            }).subscribe();
}

我可以让它更优雅吗?

标签: javaspringspring-webflux

解决方案


推荐阅读