Oya
Oya

Reputation: 903

Manage API calls with Java [Android]

I am trying to manage request calls. Here is my situation. I am using retrofit 2 with RxJava. I have a API request call in onResume method in my Fragment. When I switch tabs in my application or rotate the phone the onResume method gets called again and if the call is slow I send two same requests and get 2 identical responses. Do you have any idea how I can prevent this?

I would like to not send a second API call if the first one is ongoing or somehow merge the 2 responses into one if the calls are the same.

Thanks

Upvotes: 0

Views: 95

Answers (2)

Ramees Thattarath
Ramees Thattarath

Reputation: 1093

As you are using rxJava, the subscribe function will return a subscription object which you can dispose any where(may be in your onPause()), meaning that our activity(or life cycle mananger) will no more bother about the responses after disposal of the subscription object.Now you can expect only the latest response from server...

Upvotes: 0

Rajan Kali
Rajan Kali

Reputation: 12953

you can create a flag for wrapping api and make it false while requesting and true on response

private boolean canRequest = true;
void onResume(){
if(canRequest){
   canRequest = false;
   fetchDataUsingRetroFit(new ResponseCallBack(){
       void onResponse(){
         canRequest = true;
       }
    });
}
}

Upvotes: 1

Related Questions