Search code examples
spring-bootreactive-programming

How to get value from a Mono subscribe call


I have something like this:

mono.subscribe(val -> doSomething(val));

doSomething returns an integer. I would get and return that integer, or a Mono<int>. How can I do?


Solution

  • To return Mono<Integer> you can do the following:

    Mono<Integer> result = mono.map(value -> doSomething(value));
    

    But remember that in Reactor, nothing happens until subscribe, so don't forget to subscribe:

    result.subscribe(System.out::println);
    

    If you want to get an integer out of mono, then you can replace subscribe with block, but pay attention that this is a blocking operation:

    Integer result = mono.map(App2::doSomething).block();