Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage parallel and serial Retrofit API calls

I have 4 API calls in the same activity. 3 of them are independent of each other.I would like to call number 4 after first three finished and I am not sure the execution of first 3 in every time. I get data from database then it will call. It may 1 API call or 2 or 3 among first three. I tried to call one after another sequentially but sometimes number 4 starts before first 3 finished. some of my efforts given below:

if(true){ // data 1 is available in database

    firstRetrofitCall();

}else{

    //show no data

}
if(true){ // data 2 is available in database

    secondRetrofitCall();

}else{

    //show no data

}
if(true){ // data 3 is available in database

    thirdRetrofitCall();

}else{

    //show no data

}

fourthRetrofitCall(); // I would like to execute this after first three finished

is it possible to manage using RxJava?

like image 667
Zahidul Avatar asked Jan 28 '26 10:01

Zahidul


2 Answers

Use Rxjava2 adapter with Retrofit and then you can use Rxjava's zip operator to combine first three calls like this(assuming your calls return X,Y,Z values respectively and XYZwrapper is just container for these) and then flatMap operator to do the fourth call.

Single.zip(
            firstRetrofitCall(),
            secondRetrofitCall(),
            thirdRetrofitCall(),
            Function3<X, Y, Z, XYZwrapper> { x, y, z -> return@Function3 XYZwrapper(x, y, z) }
        )
        .subscribeOn(Schedulers.io())
        .flatMap { XYZwrapper -> fourthRetrofitCall().subscribe() }//chaining 
        .observeOn(AndroidSchedulers.mainThread())
        .subscribeBy( onError = {}, onSuccess = {})
like image 125
honey_ramgarhia Avatar answered Jan 30 '26 02:01

honey_ramgarhia


Declare a Boolean array of size 3 and initialize its indexes to false. Update the index to true in each 1st three API call's onResponse method. For example set index 0 to true for API call 1 and so on. And check in onResponse method that each of the array indexes are true if true then call the fourth API.

like image 40
Furqan Avatar answered Jan 30 '26 00:01

Furqan