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

42fyovps  于 2023-02-22  发布在  Spring
关注(0)|答案(2)|浏览(259)
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中的person

tquggr8v

tquggr8v1#

1.不要在没有任何需求的情况下订阅整个React式
1.不要在任何地方使用flatMap(),我看到你用它来进行完全同步的操作,然后只在return语句中执行Mono.just(...)
1.不要直接访问对象的字段。它们应该是私有的,使用getter和setter
1.你不需要“等待”,它是一个React式框架,本质上是异步的,所以只要在你的链上放置适当的回调函数就可以了。

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

qvk1mo1f2#

我想利用链接的优势。顺便说一句,整个过程可以简化为一个简单的片段:

Mono<Person> categoryBestPageResponseMono = Mono
    .just(Person.builder()
            .student(some1())
            .school(some2())
            .build())
    .flatMap(person -> getPassOrfail(person.student.id, person.school.number)
            .doOnSuccess(person::setPassInfo)
            .thenReturn(person));

相关问题