如何在SpringWebFlux中将mono对象转换为其他mono对象

kq0g1dla  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(1440)

我有一节这样的课

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
}

并从外部api向webclient获取数据

--- omitted ---
final Mono<PersonDto> personDto = wrapperWebClient.getPersonDto(uriComponents, params, PersonDto.class);
Mono<StudentDto> studentDto = convert(personDto);
--- omitted ---

我想将数据转换成如下所示。

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
}

这是我的尝试

--- 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 ???;
}

我的方法似乎是同步的。

bqucvtff

bqucvtff1#

你用 flatMap . 这是基本的React器,在询问堆栈溢出之前,您应该通读入门React器。

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

相关问题