'How to convert Mono object without blocking?

Suppose I have this method:

public static Mono<String> getData2() {
    return Mono.just("7");
}

I want to call this method, get back the string, convert that string to an Integer 7, and then return that integer in a non-blocking way. How can I do this?

I've tried this, but the map function is blocking (synchronous):

public static Mono<Integer> getData1() {
    return getData2().map(data -> Integer.parseInt(data));
}

I tried using flatMap instead (asynchronous):

public static Mono<Integer> getData1() {
    return getData2().flatMap(data -> Integer.parseInt(data));
}

But then I get this error: Type mismatch: cannot convert from int to Mono<? extends Integer>

So what can I do?



Solution 1:[1]

In Spring-reactor, operations, such as Mono.just, Mono.map and so on, are lazy evaluation. Nothing happens until subscribe. Blocking usually occurs in network calling or resource locking. It's another concept. If you want a asynchronous Mono, Mono.defer may be help. And subscribeOn can be used to do resource isolation.

Back to the question, Mono.just("7").map(Integer::parseInt) just gives you a mono object. In asynchronous way, we can change this to Mono.defer(() -> Mono.just("7").map(Integer::parseInt))subscribeOn(Schedulers.newBoundedElastic(xxxx)). But this may be unnecessary and meanless.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1