2

I am trying to run the main method where the main method calls another method(Bmethod) which I need to run in the background but I need the main method response immediately without waiting for Bmethod response. I need to use java reactive code(webflux).

public static void main(String[] args) {
       String abc=  Mono.just(Bmethod()).block();
        System.out.println("AAAAAAA");
    }


    public static String Bmethod() {
        System.out.println("BBBBBBBB");
        return "AACALL";

    }

I want to print AAAAAAA and then only BBBBBBBB without waiting Bmethod response. How to achieve using reactive mono Java.

sudar
  • 1,446
  • 2
  • 14
  • 26
  • I think you need to explain more in detail what it is you actually want to do. Because this can be solved in many, many different ways. For instance, what is `abc` used for, and you are not allowed to call `block` in a reactive `non-blocking` application. – Toerktumlare Feb 03 '21 at 17:13

1 Answers1

0

You'll have to switch your call to Bmethod to a supplier and move the block call to the end.

Mono<String> abcMono = Mono.fromSupplier(() -> Bmethod());
System.out.println("AAAAAAA");
String abc = abcMono.block();

Note that:

  1. the call to block defines the moment you actually need the value from your Mono, so it should not be at the beginning.
  2. in comparison to the supplier solution, your idea with just forces java to compute the argument before giving it to the function, making the wrapping useless
AdrienW
  • 3,092
  • 6
  • 29
  • 59
  • Correct me if I am wrong, but in your answer, the abcMono doesn't start processing until after "AAAAAAA" is output. I think sudar wanted abcMono to start processing in the background. While that is occurring, the foreground logic then outputs "AAAAAAA". After "AAAAAA' is output, the foreground then examines (possibly waiting) the results abcMono's background processing. – JohnC Mar 16 '23 at 00:38
  • Correct. In the absence of feedback from OP, I provided what I deemed the most simple answer. As @Toerktumlare said, there are many ways to achieve that vague behavior. Hard to say what is appropriate for OP without any further context. – AdrienW Mar 16 '23 at 10:21