I am new to Reactive Programming in java. I tried to execute the below program in asynchronous way. I mean the main thread has to complete its execution without waiting for the Mono object. But the Main thread was blocked till the subscribe method completion. Can someone make this program asynchronous?
public static void main(String[] args) {
Mono.just(getValue()).subscribe(value -> System.out.println(value));
}
public static int getValue() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return 10;
}
I tried to execute this program asynchronous and expecting this program will not wait for the Mono subcribe method should not execute and terminate immediately should not wait for 10 seconds.
In order to make call async you can create Mono.fromSupplier
and afterwards subscribeOn
a different scheduler, because by default subscription is made on main
thread.
Mono.fromSupplier(()->getValue())
.subscribeOn(Schedulers.parallel())
.subscribe(value -> System.out.println(value));