sp00m
sp00m

Reputation: 48817

Difference between Mono#then and Mono#and?

Given the following monos:

Mono<Void> mono1 = Mono.fromRunnable(() -> {
    System.out.println("sleep1");
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
    System.out.println("mono1");
});
Mono<Void> mono2 = Mono.fromRunnable(() -> {
    System.out.println("mono2");
});
Mono<Void> mono3 = Mono.fromRunnable(() -> {
    System.out.println("mono3");
});

Both:

mono1
        .then(mono2)
        .then(mono3)
        .block();

And:

mono1
        .and(mono2)
        .and(mono3)
        .block();

Have the same output:

sleep
mono1
mono2
mono3

What's the difference between Mono#then and Mono#and in this case?


From https://projectreactor.io/docs/core/release/reference/index.html#which-operator:

[If you] have a sequence but [you are] not interested in values and [you] want to switch to another Mono at the end, [use] Mono#then(mono).

[If you] want to combine publishers by coordinating their termination from 1 Mono and any source into a Mono, [use] Mono#and.

This doesn't help me finding a case where #and and #then would behave differently unfortunately.

Upvotes: 2

Views: 3592

Answers (1)

Ilya Zinkovich
Ilya Zinkovich

Reputation: 4410

Mono#and just "joins the termination signals from current mono and another source into the returned void mono". It always returns Mono<Void> and only lets you coordinate termination of two Monos.

Mono#then lets you chain two Monos together and the final result will be determined by the Mono passed as a parameter. In this sense, Mono#then is a more primitive version of Mono#flatMap, the only difference is that inside of Mono#flatMap you have access to the result of the previous Mono in a chain that you can transform into another Mono instance.

In addition to that, with Mono#then the operations will be executed sequentially, while with Mono#and there is no guarantee of ordering (at least from the documentation).

Upvotes: 3

Related Questions