Deepak Bhimaraju
Deepak Bhimaraju

Reputation: 81

When does reactor execute a subscription chain?

The reactor documentation states the following:

Nothing happens until you subscribe

If that was true, why do I see a java.lang.NullPointerException when I run the following code snippet, which has a reactor chain without a subscription?

    @Test
    void test() {
        String a = null;
        Flux.just(a.toLowerCase())
                .doOnNext(System.out::println);
    }

Upvotes: 1

Views: 712

Answers (1)

Stepan Tsybulski
Stepan Tsybulski

Reputation: 1171

Deepak,

Nothing happens means the data will not be flowing through the chain of your functions to your consumers until a subscription happens.

You're getting NPE because Java tries to compute the value which is given to a hot operator just() on the Flux definition step.

You can also convert just() to a cold operator using defer() so you will receive NPE only after a subscription happened:

public Flux<String> test() {
    String a = null;
    return Flux.defer(() -> Flux.just(a.toLowerCase()))
            .doOnNext(System.out::println);
}

Please, read more about hot vs hold operators.

Update:

Small example of cold and hot publishers. Each time new subscription happens cold publisher's body is recalculated. Meanwhile, just() is only producing time that was calculated only once at definition time.

Mono<Date> currentTime = Mono.just(Calendar.getInstance().getTime());
Mono<Date> realCurrentTime = Mono.defer(() -> Mono.just(Calendar.getInstance().getTime()));

// 1 sec sleep
Thread.sleep(1000);
currentTime.subscribe(time -> System.out.println("Current Time " + time.getTime()));
realCurrentTime.subscribe(time -> System.out.println("Real current Time " + time.getTime()));

Thread.sleep(2000);
currentTime.subscribe(time -> System.out.println("Current Time " + time.getTime()));
realCurrentTime.subscribe(time -> System.out.println("Real current Time " + time.getTime()));

The output is:

Current Time 1583788755759

Real current Time 1583788756826

Current Time 1583788755759

Real current Time 1583788758833

Upvotes: 3

Related Questions