I have 4 blocking operations and would like to run them in parallel by using RxJava Single/Flowable.
The test code that I wrote to check parallelism is:
final Single<Boolean> f1 = Single.fromCallable(() -> {
TimeUnit.SECONDS.sleep(2);
System.out.println("f1 " + Thread.currentThread().getName());
return true;
});
final Single<Boolean> f2 = Single.fromCallable(() -> {
System.out.println("f2 " + Thread.currentThread().getName());
return true;
});
final Single<Boolean> f3 = Single.fromCallable(() -> {
TimeUnit.SECONDS.sleep(1);
System.out.println("f3 " + Thread.currentThread().getName());
return true;
});
final Single<Boolean> f4 = Single.fromCallable(() -> {
System.out.println("f4 " + Thread.currentThread().getName());
return true;
});
Flowable.fromArray(f1, f2, f3, f4)
.flatMap(Single::toFlowable)
.parallel(4)
.runOn(Schedulers.io())
.sequential()
.ignoreElements()
.blockingAwait();
However they run all on the same thread, sequentially giving the following output:
f1 Test worker
f2 Test worker
f3 Test worker
f4 Test worker
despite the time delays in f1 and f3...
Using Flowable.parallel
works fine with flowables of values but now in this case. So I am missing something.
How can I make my code work or how can I run callables in parallel in a elegant way by using RxJava?