1
votes

The projectReactor documentation says that Mono::flatMap is asynchronous, as shown below.

So, I can write all my methods to return Mono publishers like this.

public Mono<String> myMethod(String name) {
    return Mono.just("hello " + name);
}

and use it with Mono::flatMap like this:

Mono.just("name").flatMap(this::myMethod);

Does this make the execution of my method asynchronous? Does this make my code more reactive, better and faster than just using Mono::map? Is the overhead prohibitive for doing this for all my methods?

public final Mono flatMap(Function<? super T,? extends Mono<? extends R>> transformer)

Transform the item emitted by this Mono asynchronously, returning the value emitted by another Mono (possibly changing the value type).

enter image description here

1
@AbhinabaChakraborty You are still partially correct.Concurrent Bhai
@ConcurrentBhai I might be. Can you please suggest where I am wrong , so that I can improveAbhinaba Chakraborty

1 Answers

1
votes

Does this make the execution of my method asynchronous?

Let's go to the definition of Asynchronous for this:

Asynchronous programming is a means of parallel programming in which a unit of work runs separately from the main application thread and notifies the calling thread of its completion, failure or progress.

Here your unit of work is happening in the same thread, unless you do a subscribeOn with a Scheduler. So this isn't async.

Does this make my code more reactive, better and faster than just using Mono::map?

No way. Since in this case, the publisher Mono.just("hello " + name) immediately notifies the subscriber that I am done, the thread in which the processing was going on immediately picks up that event from the event loop and starts processing the response.

Rather, this might cause few more operations internally than a map which simply transforms the element.

Thus, ideally, you should use a flatMap when you have an I/O Operation (like DB calls) or Network calls, which might take some time, which you can utilize in doing some other task , if all the threads are busy.