起始点为Mono<Person>
我希望能够调用多个函数来对其执行操作。这些函数采用 Mono<Person>
并将返回Mono<String>
或Mono<Integer>
即可能是数据库中条目的 ID 和 REST 调用的结果。
我正在努力解决的是如何将这些调用链接在一起,以便我可以返回 Mono<Person>
进行第二次(以及任何 future 的)调用。
下面的代码可以工作,但我想知道是否有更好的模式使用不同的 Mono 函数来消除中间 map() 调用的需要。
import reactor.core.publisher.Mono;
public class Person {
private String name;
private Integer age;
Person(String name, Integer age) {
this.name = name;
this.age = age;
}
private String getName() { return this.name; }
private void setName(String name) { this.name = name; }
static Mono<Person> p = Mono.just(new Person("Bob", 42));
public static void main(String[] args) {
// Want to call doThing1() first, once that
// returns perform doThing2()
Mono<Person> personMono = p.flatMap(person -> doThing1(person)
.map(s -> person))
.flatMap(person -> doThing2(person)
.map(i -> person));
personMono.subscribe();
}
// i.e. store in DB and return ID string
private static Mono<String> doThing1(Person person) {
return Mono.just("12345");
}
// i.e. perform some operation i.e. REST
// call and return status code
private static Mono<Integer> doThing2(Person person) {
return Mono.just(200);
}
}
最佳答案
您可以使用 thenReturn
代替 map
运算符更具可读性和表达力。
public static void main(String[] args) {
Mono<Person> personMono = p.flatMap(person -> doThing1(person).thenReturn(person))
.flatMap(person -> doThing2(person).thenReturn(person));
personMono.subscribe();
}
不幸的是,我不知道有哪个运算符(operator)可以一步完成此操作。
关于java - 将 Monos 链接在一起,其中函数返回结果代码而不是完整对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57570235/