본문 바로가기

Back/Java

[Java/Reactor] Mono then() 동작 흐름 테스트

오늘의 주제

Mono then() 메서드가 어떻게 동작하는지 흐름 파악하기.

 

 

 

배경

Java Reactive Programing 으로 채팅서버 구현중.

then()의 역할에 대해 의구심이 들었다.

A.then(B) 인 경우에 A의 값이 반환된 후 B가 실행된다고 생각하고 있었는데

A가 끝나기전 B가 실행되고 실행이 끝나버리는 경우가 발생.

 

 

 

목표

- sleep 동작하는 메서드 생성하기

- A.then(B) 에서 sleep을 걸고 A,B가 어떻게 실행되는지 확인하기

 

 

 

실행하기

Mono<Void>로 리턴하는 메서드를 두개를 then으로 연결해서 실행

    @Test
    void mono_then_test() {
        first_sequence().then(second_sequence()).subscribe();
    }

    Mono<Void> first_sequence() {
        System.out.println("------------first_sequence------------");
        return Mono.create(sink -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("first_sequence: " + i);
                if (i == 5) sink.success();
            }
        });
    }

    Mono<Void> second_sequence() {
        System.out.println("------------second_sequence------------");
        return Mono.create(sink -> {
            System.out.println("------second_sequence mono start------");
            sleep_mono().block();
            sink.success();
            System.out.println("------second_sequence mono end------");
        });
    }

    Mono<Long> sleep_mono() {
        System.out.println("sleep_mono");
        return Mono.delay(Duration.ofSeconds(10L));
    }

결과

------------first_sequence------------
------------second_sequence------------
first_sequence: 0
first_sequence: 1
first_sequence: 2
first_sequence: 3
first_sequence: 4
first_sequence: 5
------second_sequence mono start------
sleep_mono
------second_sequence mono end------
first_sequence: 6
first_sequence: 7
first_sequence: 8
first_sequence: 9

 

 

 

결론

A.then(B)의 경우,

A실행 후 B가 바로 실행된다.

Mono에 감싸져 있는 경우에만 A 메서드의 success signal이 오면 B메서드를 실행한다.

sink.sucess() 가 호출되지않으면 B메서드의 mono는 실행되지않는다.

mono delay가 원하는대로 sleep기능을 동작하게 하려면 block()을 걸어야 한다.