In my application, requests are executed at once for the entire list, how can you make them run as if they were chained? At first it was executed for the 1st element, after it was executed, it starts being executed for the second.

private void loadJSON() { Call<List<Integer>> call = request.getTopStories(); call.enqueue(new Callback<List<Integer>>() { @Override public void onResponse(Call<List<Integer>> call, Response<List<Integer>> response) { topStories = response.body(); loadDetails(); } @Override public void onFailure(Call<List<Integer>> call, Throwable t) { Toast.makeText(MainActivity.this, R.string.error, Toast.LENGTH_LONG).show(); } }); } private void loadDetails(){ for (Integer id : topStories) { request.getTopStore(id).enqueue(new Callback<Model>() { @Override public void onResponse(Call<Model> call, Response<Model> response) { models.add(response.body()); topStoriesAdapter.notifyDataSetChanged(); } @Override public void onFailure(Call<Model> call, Throwable t) { Toast.makeText(MainActivity.this, R.string.error, Toast.LENGTH_LONG).show(); } }); } } 

    1 answer 1

    I propose a variant using recursion:

    Add a field to the class in which these methods are located:

     private int mLoadPosition; 

    Before calling the loadJSON() method, initialize the mLoadPosition field:

     mLoadPosition = -1; 

    and change the loadDetails() method:

     private void loadDetails() { mLoadPosition++; if (mLoadPosition == topStories.size()) { return; } int id = topStories.get(mLoadPosition); request.getTopStore(id).enqueue(new Callback<Model>() { @Override public void onResponse(Call<Model> call, Response<Model> response) { models.add(response.body()); topStoriesAdapter.notifyDataSetChanged(); loadDetails(); } @Override public void onFailure(Call<Model> call, Throwable t) { Toast.makeText(MainActivity.this, R.string.error, Toast.LENGTH_LONG).show(); } }); } 

    Or you can use synchronous requests, but then you have to manually implement the execution of requests in a stream other than the UI stream.

    • Thank you, everything works correctly, only I wanted to clarify the second step, namely the initialization of the field, because you can immediately declare the field as `private int mLoadPosition = -1;` so that it will not be initialized once again into onCreate . - Morozov
    • @Morozov; In this case, if you run loadJSON() second time, then the loadDetails() method will not work correctly. - post_zeew
    • it seems like everything is good, in any case, if you already know how to rule, thanks) - Morozov