Firstly, you're using subscribeOn()
for each observable so it's already executing in parallel.
Is there a way to get the response at the same time while fetching the data in parallel. for example, the first endpoint could take 5 seconds while the second takes 7 seconds but the end response would be available after 7 seconds.
For this, you can use Observable.zip
like the following where the time required is the
maximum of two calls:
val disposable = Observable.zip(
firstNetworkCall().subscribeOn(Schedulers.io()),
secondNetworkCall().subscribeOn(Schedulers.io()),
BiFunction{
firstResonse: ResponseOneType,
secondResponse: ResponseTwoType ->
combineResult(firstResponse, secondResponse) }))
.observeOn(AndroidSchedulers.mainThread())
.subscribe { it -> doSomethingWithIndividualResponse(it) }
This article may help to visualize how it's working underneath.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…