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?