Flux를 원하는 값만 필터링 하는 방법을 소개한다.
@Test
void testFindPersonById() {
Flux<Person> personFlux = personRepository.findAll();
final int id = 3;
Mono<Person> personMono = personFlux
.filter(person -> person.getId() == id)
.next();
personMono.subscribe(person -> System.out.println(person.toString()));
}
위 filter()
의 조건문을 통과하는 데이터만 필터링해서 Flux로 돌려준다.
next()
메소드는 처음 오는 데이터를 받아서 Mono로 반환해 주는 메소드 이다.
따라서 위 코드는 id가 3인 Person 중 첫번째 데이터를 Mono로 반환하는 코드이다.
@Test
void testFindPersonByIdNo() {
Flux<Person> personFlux = personRepository.findAll();
final int id = 1289;
Mono<Person> personMono = personFlux
.filter(person -> person.getId() == id)
.next();
personMono.subscribe(person -> System.out.println(person.toString()));
}
위 코드는 어떠한 출력도 가지지 않는다.
id가 1289인 person이 존재하지 않기 때문에 filter()
는 빈 Mono를 반환한다.
따라서 각각의 요소마다 작동하는 subscribe()
의 print문은 어떠한 값도 출력하지 못한다.
따로 오류가 나진 않기 때문에, 하나의 값을 반환해야 하는 메소드에서 여러개 또는 0개의 값을 반환했을 때에도 오류가 발생하지 않는다.
@Test
void testFindPersonByIdNotFoundWithException() {
Flux<Person> personFlux = personRepository.findAll();
final int id = 1289;
Mono<Person> personMono = personFlux
.filter(person -> person.getId() == id)
.single();
personMono.subscribe(person -> System.out.println(person.toString()));
}
아까 filter()
를 테스트 할 때 코드와 거의 비슷하지만, next()
가 single()
로 바뀌었다.
next()
와 single()
둘 다 하나의 데이터를 Mono로 반환한다는 공통점이 있다.
하지만 single()
은 데이터가 없거나 2개 이상이라면 예외가 발생하게 된다.
@Test
void testFindPersonByIdNotFoundWithException() {
Flux<Person> personFlux = personRepository.findAll();
final int id = 1289;
Mono<Person> personMono = personFlux
.filter(person -> person.getId() == id)
.single();
personMono.doOnError(throwable -> System.out.println("error occured"))
.subscribe(person -> System.out.println(person.toString()));
}
위와 같이 예외가 발생했을 때의 처리를 돕는다.
하지만 doOnError()
는 단순히 예외가 발생했을 때 실행될 뿐이라서 subscribe()
할 때에는 여전히 예외가 발생한다.
@Test
void testFindPersonByIdNotFoundWithException() {
Flux<Person> personFlux = personRepository.findAll();
final int id = 1289;
Mono<Person> personMono = personFlux
.filter(person -> person.getId() == id)
.single();
personMono.doOnError(throwable -> System.out.println("error occured"))
.onErrorReturn(Person.builder().build())
.subscribe(person -> System.out.println(person.toString()));
}
위와 같이 예외가 발생했을 때, subscribe()
를 실행하지 않고 그 대신 반환할 값을 지정해줄 수 있다.
즉 subscribe()
는 실행되지 않고, 비어있는 Person 객체가 반환될 것이다.
subscribe()
는 비어있는 Person 객체를 가지고 실행되기 때문에 예외가 발생하지 않게 된다.
비어있는 Mono가 아니라, Mono이지만 Person 객체의 모든 값이 null인 상황이다.