如何在 Mono.flatMap 中等待返回单值函数?

问题描述 投票:0回答:2
Mono<Student> studentMono = some1();
Mono<School> schoolMono = some2();

Mono<Person> categoryBestPageResponseMono = Mono.zip(studentMono, schoolMono).flatMap(data -> {
   Student student = data.getT1();
   School school = data.getT2();

   Person person = Person.builder()
                         .student(student)
                         .school(school)
                         .build();
   

   return Mono.just(person);
}).flatMap(person -> {
   Mono<PassInfo> passInfoMono= getPassOrfail(person.student.id, person.school.number);

   //pass info is null when first and second get from cache not null
   passInfoMono.subscribe(passInfo -> person.setPassInfo(passInfo));
   return Mono.just(person);
});

在上面的源代码中,我总是为 passInfo 获取 null。

如何等待getPassOrfail操作,将passInfo放入setter中的personinfo中?

spring-webflux reactive-programming project-reactor spring-webclient
2个回答
1
投票

我会利用链接的优势:

...
.flatMap(person -> getPassOrfail(person.student.id, person.school.number)
        .doOnSuccess(person::setPassInfo)
        .thenReturn(person));

1
投票
  1. 不要在没有任何需要的情况下在整个反应过程中的任何地方订阅
  2. 不要在任何地方使用
    flatMap()
    ,我看到你正在使用它进行完全同步的操作,然后只是在 return 语句中执行
    Mono.just(...)
    。对于同步操作,有
    .map()
    运算符
  3. 不要直接访问对象的字段。他们应该是私有的,使用 getters 和 setters
  4. 你不需要“等待”。它是反应式框架,本质上是异步的,因此只需将适当的回调放在链上即可。
    Mono.zip(studentMono, schoolMono)
            .map(data -> {
                Student student = data.getT1();
                School school = data.getT2();

                Person person = Person.builder()
                        .student(student)
                        .school(school)
                        .build();
                return person;
            })
            .flatMap(person -> getPassOrfail(person.getStudent().getId(), person.getSchool().getNumber())
                    .map(passInfo -> {
                        person.setPassInfo(passInfo);
                        return person;
                    })
            );
© www.soinside.com 2019 - 2024. All rights reserved.