【问题标题】:Smart way to handle nested flux operations处理嵌套通量操作的智能方法
【发布时间】:2020-10-07 09:33:04
【问题描述】:

我有 2 个查询方法 (findByName/findAnotherName)。

它们都返回 Mono

我通过比较这两种方法的结果来做一些逻辑,然后在嵌套的 Flux 操作中返回其中一个。

它可能有一个聪明的方法来达到同样的结果。

以下是代码sn-p:

private Mono<List<Student>> find(String name) {

    return repo.findByName(name)
            .flatMap((List<Student> students) -> {

                return repo.findAnotherName(anothName, 1).collectList()
                        .flatMap((List<Student> anotherStudents) -> {

                            //do some logic

                            return Mono.just(students);
                        });

            });

}

提前致谢。

【问题讨论】:

  • findAnotherName 是否依赖于 findByName 的结果?
  • 是的,这取决于 findByName 的结果。根据结果​​,处理业务逻辑,然后返回计算结果的Mono。

标签: java reactor


【解决方案1】:

https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#zipWhen-java.util.function.Function-java.util.function.BiFunction-

如果您的 //do some logic 是同步的,那么我可以建议类似

private Mono<List<Student>> find(String name) {

    return repo.findByName(name)
            .zipWhen((List<Student> students) -> {
                return repo.findAnotherName(anothName, 1).collectList();
            }, (students, anotherStudents) -> {
                //some sync logic
                return students;
            });
}

但是如果逻辑也是异步的,那么

private Mono<List<Student>> find(String name) {

    return repo.findByName(name)
            .zipWhen((List<Student> students) -> {
                return repo.findAnotherName(anothName, 1).collectList()
                        .flatMap(anotherStudents -> someAsyncMethod(anotherStudents));
            }, ((students, o) -> students));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    • 2016-03-05
    • 1970-01-01
    相关资源
    最近更新 更多