How to make multiple calls with Retrofit?

…衆ロ難τιáo~ 提交于 2019-12-08 01:57:31

问题


I need to make multiple calls to API REST with Retrofit and show the response in a ListView, but I don't know how to do this and this code doesn't work.

Model

@GET("apks/{sha256}")
    Call<DatoAPI> getTask2(@Path("sha256") String hash, @Query("Authorization") String key);

Implementation

for (String s: hash) {                                          
    Call<DatoAPI> call = services.getTask2(s, API.API_KEY);
    call.enqueue(new Callback<DatoAPI>() {
        @Override
        public void onResponse(Call<DatoAPI> call, Response<DatoAPI> response) {
            if (response.isSuccessful()) {
                datoAPI = response.body();
                items.add(datoAPI.getApp());
            }
        }

        @Override
        public void onFailure(Call<DatoAPI> call, Throwable t) {
            Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();
        }
    });
}

Also I tried with call.execute() and same problem I want to show this response in a ListView but it doesn't work.


回答1:


First off all you need to understand the differences between Retrofit's Call#enqueue() and Call#execute() methods.

  1. enqueue() method is Asynchronous which means you can move on to another task before it finishes

  2. execute() method is Synchronous which means, you wait for it to finish before moving on to another task.

And in your case you're using for loop to execute multiple request in a single stretch.

Now, if you use for loops to execute network operation, the network operation will not stop for loops from going to next iteration. Do not expect that the API will always respond in a fast enough way before going to for loops next iteration. That's a bad idea.

If you use Retrofit's execute() method, it will not allow you to continue to next line (or iteration) as its Synchronous behavior, plus it throws NetworkOnMainThreadException and IOException. Hence, you need to wrap the request in an AsyncTask and handle IOException.

I'd recommend you to use RxAndroid with RxJava instead of using for loops. There are plenty of tutorials out there on this topic.

Refer the following StackOverflow questions to solve your problem.

  1. How to make multiple request and wait until data is come from all the requests in Retrofit 2.0 - Android?
  2. Asynchronous vs synchronous execution, what does it really mean?

Adjust the code as per your requirements.

Good luck!



来源:https://stackoverflow.com/questions/52101253/how-to-make-multiple-calls-with-retrofit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!