How to apply Synchronous task for retrofit android
Asked Answered
H

2

5

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?

Heterogynous answered 17/5, 2016 at 12:14 Comment(0)
G
10

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.

Geisha answered 17/5, 2016 at 12:29 Comment(0)
G
0

You can make synchronous retrofit requests by not passing a callback

for(int i=0; i< mFileArrayList.size();i++){ 
        NotesResponse response = WebServiceManager.getInstance().getFrogService().postNotes("HI", "Hello", "Done");
}

make sure you run this code off the main thread. For reference check this tutorial https://futurestud.io/blog/retrofit-synchronous-and-asynchronous-requests

Genseric answered 17/5, 2016 at 12:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.