I would use the Flowable Object from rxJava.
public static void main(String[] args) throws Exception {
Flowable.fromCallable(() -> addTwoNumbersAsync(5, 4))
.subscribe(result -> System.out.println(result));
Thread.sleep(1000);
}
private static int addTwoNumbersAsync(int a, int b) {
return a + b;
}
The method call and the System print will be in a rxJava Thread, and not in the main Thread. You can specify the threadpool on which the Flowable will operate, by adding .subscribeOn(Schedulers.computation())
before the .subscribe(...)
for example.
You can also make a method, which returns the Flowable, which is closer to your original example.
public static void main(String[] args) throws Exception {
addTwoNumbersAsync(5,4)
.subscribe(result -> System.out.println(result));
Thread.sleep(1000);
}
private static Flowable<Integer> addTwoNumbersAsync(int a, int b) {
return Flowable.fromCallable(() -> a+b);
}