Search code examples
project-reactornonblockingreactor

Project Reactor: Sum two Mono<Integer> without blocking


Suppose that we have:

Mono<Integer> int1 = Mono.just(1) and Mono<Integer> int2 = Mono.just(10). I would like get the sum of these two integer without blocking.

In the blocking way I would do this: Mono<Integer> result = Mono.just(int1.block() + int2.block())

Thanks in advance!


Solution

  • Try zip:

    Mono<Integer> int1 = Mono.just(1); //or any other mono, including lazy one
    Mono<Integer> int2 = Mono.just(10); //same
    
    
    Mono<Integer> sum = Mono.zip(
        int1, int2,
        //zip defaults to producing a Tuple2
        //but for the 2 args version you can provide a BiFunction
        (a, b) -> a + b
    );
    
    //if you want to verify, eg. in a test:
    StepVerifier.create(sum)
        .expectNext(11)
        .verifyComplete();