Execute the current flow while background process is running - mono reactive programming

Viewed 204

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.

1 Answers

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
Related