G
G
giksen2021-03-21 16:46:45
Android
giksen, 2021-03-21 16:46:45

How to correctly make multiple requests using Retrofit in MVVM pattern?

I have a LiveData> mAllCompanies field that holds the objects I need. For each such object, I need to make a request, get the data and assign the value of the new list of data to the mAllCompanies field. The problem is that a lot of threads start up and you can't get what you need.
The API allows you to get only one object of the required class at a time.
NetworkService - a class that implements the retrofit logic

private static class getAllCompaniesProfilesTask extends AsyncTask<List<Company>,Void,List<Company>>{
        private NetworkService networkService;
        List<Company> companiesToGet;
        List<Company> companiesToReturn;
        getAllCompaniesProfilesTask(NetworkService networkService) {
            this.networkService = networkService;
        }
        @Override
        protected List<Company> doInBackground(List<Company>... lists) {
            companiesToGet = lists[0];
            companiesToReturn = new ArrayList<>();
            for(int i = 0;i < companiesToGet.size(); ++i){
                networkService.getJSONApi()
                        .getCompanyProfileBySymbol(companiesToGet.get(i).ticker)
                        .enqueue(new Callback<Company>() {
                            @Override
                            public void onResponse(Call<Company> call, Response<Company> response) {
                                companiesToReturn.add(response.body());
                            }
                            @Override
                            public void onFailure(Call<Company> call, Throwable t) {
                                System.out.println("Failed to get data from network");
                            }
                        });
            }
            companiesToGet.clear();
            companiesToGet.addAll(companiesToReturn);
            return companiesToGet;
        }
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question