0

I constructed MVVM and get data from Network by Retrofit 2. Getting data flow goes like this: MainActivity - > ViewModel -> Repository -> APiService. So, I call enqueu from the Repository, like this:

public List<Result> getArticles() {
    final List<Result>[] articles = new List[]{new ArrayList<>()};
    Log.d(TAG, "getArticles");
    ApiService.getService().getArticles("test", "thumbnail").enqueue(new Callback<Example>() {
        @Override
        public void onResponse(Call<Example> call, Response<Example> response) {
            Log.d(TAG, "onResponse");
            if (response.isSuccessful()) {
                Log.d(TAG, "isSuccessful");
                articles[0] = response.body().getResponse().getResults();   
            }
        }

        @Override
        public void onFailure(Call<Example> call, Throwable t) {
            Log.d(TAG, "onFailure");
        }
    });
    return articles[0];
}

And I call getArticles from my ViewModel like this:

public List<Result> getArticleList() {
    Log.d(TAG, "getArticleList");
    articleRepository = new ArticleRepository();
    articleRepository.getArticles();
    return articleList;
}

However, my enqueue doesn't work and I spent a couple of hours to figure out why, still can't. The only thing I have noticed is that when I make a call not from the ViewModel, but from MainActivity, enqueue does work!!! Can anyone tell me what am I missing here? Why the same thing doesn't work from ViewModel? I think there is some threading or lifecycle problem, but can't figure out what exactly.

Also, noticed that when getting data I try to print in MainActivity, it doesn't work:

for (Result article : articleList) {
    Log.d(TAG, article.getSectionName());
}

But when I print it from retrofit enqueue onResponse callback it does work. What's the problem here?

sunflower20
  • 469
  • 3
  • 8
  • 20
  • Sorry, my bad, the reason was small code error.I would rather downvote myself:D However, the list is still not get logged from the MainActivity. – sunflower20 Jun 16 '18 at 10:39

1 Answers1

2

Try to change your ViewModel to return articleRepository.getArticles()

public List<Result> getArticleList() {
    Log.d(TAG, "getArticleList");
    articleRepository = new ArticleRepository();
    return articleRepository.getArticles();
}
eurosecom
  • 2,932
  • 4
  • 24
  • 38
  • Thank you very much, I found it later when posted the question – sunflower20 Jun 16 '18 at 15:13
  • do you have any idea why the list is not getting logged from the MainActivity, this is getting very concerning – sunflower20 Jun 17 '18 at 04:30
  • Your Retrofit call is asynchronous. You have to use callback to your activity to get result in UI. May be help https://stackoverflow.com/questions/41160019/how-can-i-update-activity-fragment-ui-from-retrofit-onresponse – eurosecom Jun 17 '18 at 07:31
  • Thanks! Got it, I called setValue in OnResponse and made ui changes in LiveData onChanged callback – sunflower20 Jun 17 '18 at 14:29