Member-only story
RxJava 2: Parallel Multiple Network Calls Made Easy

In my previous blog, I have shown that how we could connect multiple network call together easily using RxJava 2. But there’s a drawback with the previous approach, as they are still called sequentially.
Let see how we could make them parallel.
Connecting 2 networks call
The slower version
When we use mergeWith
as below to combine two network call…
val disposable = firstNetworkCall()
.mergeWith(secondNetworkCall())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { it -> doSomethingWithIndividualResponse(it) }
The time required would be the total time needed by firstNetworkCall
and secondNetworkCall
as shown in diagram below.

However, since firstNetworkCall
and secondNetworkCall
are not related to each other, why can't we make them parallel?
The Parallel Version
To make it parallel, for each of the Observable, put a subscibeOn
on it
So the code looks like below
val disposable = firstNetworkCall().subscribeOn(Schedulers.io())
.mergeWith(secondNetworkCall().subscribeOn(Schedulers.io())
// .subscribeOn(Schedulers.io()) // not needed anymore
.observeOn(AndroidSchedulers.mainThread())
.subscribe { it -> doSomethingWithIndividualResponse(it) }
However, this looks a little confusing. We could make it slightly clearer instead of using mergeWith
, use Observable.merge
val disposable = Observable.merge(
firstNetworkCall().subscribeOn(Schedulers.io()),
secondNetworkCall().subscribeOn(Schedulers.io()))
.observeOn(AndroidSchedulers.mainThread())
.subscribe { it -> doSomethingWithIndividualResponse(it) }
The result will look something like below where the time is just the maximum of 2 two call (and perhaps with some slight overhead)