Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply Synchronous task for retrofit android

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?

like image 541
Deepak Sharma Avatar asked Jan 06 '23 01:01

Deepak Sharma


1 Answers

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.

like image 140
Karol Żygłowicz Avatar answered Jan 30 '23 00:01

Karol Żygłowicz