I know it's an old old thread, but since Rxjava (now it's v3) came out, my favorite way to do parallel programming is through its flatMap by the following several lines. (sometimes but not very intuitive at the first sight)
// Assume we're in main thread at the moment
Flowable.create(...) // upstream data provider, main thread
.map(...) // some transformers?? main thread
.filter(...) // some filter thread
.flatMap(data -> Flowable.just(data)
.subscribeOn(Schedulers.from(...your executorservice for the sub worker.....), true) // true is to delay the error.
.doOnNext(this::process)
, MAX_CONCURRENT) // max number of concurrent workers
.subscribe();
You can check it's javadoc to understand the operators.
Rxjava 3- Flowable
A simple example:
Flowable.range(1, 100)
.map(Object::toString)
.flatMap (i -> Flowable.just(i)
.doOnNext(j -> {
System.out.println("Current thread is ");
Thread.sleep(100);
}).subscribeOn(Schedulers.io()), true, 10)
.subscribe(
integer -> log.info("We consumed {}", integer),
throwable -> log.error("We met errors", throwable),
() -> log.info("The stream completed!!!"));
And for your case:
for(Object object: objects) {
Result result = compute(object);
list.add(result);
}
We could try:
Flowable.fromIterable(objects)
.flatMap(obj ->
Flowable.just(compute(obj)).subscribeOn(Schedulers.io()), true, YOUR_CONCURRENCY_NUMBER))
.doOnNext(res -> list.add(res))
.subscribe()
Bonus points: if you need to add some ordering, let's say for example, odd number all go to worker1, even number worker2, etc. Rxjava can achieve that easily by groupBy and flatMap operators together. I won't go too details about them here. Enjoy playing :)))
Result result = compute(object);
?