I am using retrofit API in one of my app. Below is the code :-
for(int i=0; i< mFileArrayList.size();i++){
WebServiceManager.getInstance().getFrogService().postNotes("HI", "Hello", "Done", new Callback<NotesResponse>() {
@Override
public void success(NotesResponse response, retrofit.client.Response response2) {
System.out.println(response);
Toast.makeText(AllKPIActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
@Override
public void failure(RetrofitError error) {
System.out.println(error);
Toast.makeText(AllKPIActivity.this, "Fail", Toast.LENGTH_SHORT).show();
}
});
}
What is happening is sometime before success comes, loop goes ahead and failure comes. What i want is when first success comes, then only the loop moves ahead. Please help, how can i achieve this?
If I were you I would reorganize the code to do the loop manually. Something like this
int i = 0;
private void fowardLoop(){
if(i => mFileArrayList.size()){
return; //loop is finished;
}
i++;
WebServiceManager.getInstance().getFrogService().postNotes("HI", "Hello", "Done", new Callback<NotesResponse>() {
@Override
public void success(NotesResponse response, retrofit.client.Response response2) {
System.out.println(response);
Toast.makeText(AllKPIActivity.this, "Success", Toast.LENGTH_SHORT).show();
forwardLoop(); // loop continues only if you get the success callback from previous request.
}
@Override
public void failure(RetrofitError error) {
System.out.println(error);
Toast.makeText(AllKPIActivity.this, "Fail", Toast.LENGTH_SHORT).show();
// the loop breaks when there is failure callabck.
}
});
}
just use the forwardLoop() method to start the loop where you want
The retrofit is still asynchronous but the app behaves as you want. Hope it will be helpfull I didn't test this solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With