0

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?

Kingamere
  • 9,496
  • 23
  • 71
  • 110
  • 2
    Calling `map` on a `Mono` is not a synchronous, blocking call. What makes you think that it is? – Jesper May 10 '22 at 14:52
  • @Jesper Well, I'm not so sure of the terminology. Based on this answer: https://stackoverflow.com/questions/49115135/map-vs-flatmap-in-reactor , synchronous is different from non-blocking. – Kingamere May 10 '22 at 16:02
  • The accepted answer on that question explains that `map` is a non-blocking operation. – Jesper May 11 '22 at 07:24

1 Answers1

0

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.

shanfeng
  • 503
  • 2
  • 14