[英]How to convert Mono object to other Mono object in Spring Webflux
I have a class like this我有这样的课
public class Person {
private String name;
private String age;
private Boolean student;
...
//
getters and setters
}
public class PersonDto {
private List<Person> persons
private Person president
//
getters and setters
}
and get data to webclient from external API并从外部 API 获取数据到 webclient
--- omitted ---
final Mono<PersonDto> personDto = wrapperWebClient.getPersonDto(uriComponents, params, PersonDto.class);
Mono<StudentDto> studentDto = convert(personDto);
--- omitted ---
and I want to transform data Mono DTO like below.我想像下面这样转换数据 Mono DTO。
public class Student {
// no constructors
private String name;
private String age;
private Boolean student;
...
//
getters and setters
}
public class StudentDto {
private List<Student> students;
private Student represent;
...
//
getters and setters
}
it's my try这是我的尝试
--- omitted ---
private Mono<StudentDto> convert(Mono<PersonDto> personDto) {
StudentDto studentDto = new StudentDto();
personDto.map(
persons -> {
studentDto.setStudents(
persons.getPersons()
.stream().filter(person -> person.isStudent())
.collect(toList())
);
studentDto.setRepresent(
persons.getRepresent().isStudent()
);
}
)
return ???;
}
My approach seems to be synchronous.我的方法似乎是同步的。
you use flatMap
.你使用flatMap
。 This is basic reactor and you should read through the Getting started reactor before asking on stack overflow.这是基本反应器,您应该在询问堆栈溢出之前通读入门反应器。
private Mono<StudentDto> convert(Mono<PersonDto> personDto) {
return personDto.flatMap(personDto -> {
final StudentDto studentDto = new StudentDto();
studentDto.setStudents(
persons.getPersons()
.stream().filter(person -> person.isStudent())
.collect(toList())
);
studentDto.setRepresent(
persons.getRepresent().isStudent()
);
return Mono.just(studentDto);
})
}
Just return Mono
with map只需使用地图返回Mono
private Mono<StudentDto> convert(Mono<PersonDto> personDto) {
return personDto.map(
persons -> {
StudentDto studentDto = new StudentDto();
studentDto.setStudents(
persons.getPersons()
.stream().filter(person -> person.isStudent())
.collect(toList())
);
studentDto.setRepresent(
persons.getRepresent().isStudent()
);
}
);
}
The main difference between map
and flatMap
is synchronicity . map
和flatMap
的主要区别在于同步性。
If you want handle another asynchronous one, use flatMap
.如果要处理另一个异步,请使用flatMap
。
Or, if you just want to reformat the output of the Mono/Flux
, use map
.或者,如果您只想重新格式化Mono/Flux
的输出,请使用map
。
There is transform
method in Mono class. Mono类中有transform
方法。
return Mono.fromFuture(step1.callFuture(input))
.doOnSuccess(this::logJsonInput)
.transform(otherService::calculate);
where在哪里
OtherService {
public Mono<Result> calculate(Mono<Step1Output> input) {
//...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.