未调用我的观察者回调,您能指出我做错了什么吗?我的应用程序非常简单,因为我只是在测试这种体系结构
MainActivity代码
viewModel = ViewModelProviders.of(this).get(UpcomingMoviesViewModel.class);
viewModel.getUpcomingMovies().observe(this, upcomingMovies -> {
// NOT CALLED !!!
for(UpcomingMovies movie : upcomingMovies) {
Log.d("Upcoming", "Movie - " + movie.movie.title);
}
});
ViewModel代码
private LiveData<List<UpcomingMovies>> mUpcomingMovies;
private MovieRepository movieRepository;
public UpcomingMoviesViewModel(@NonNull Application application ) {
super(application);
movieRepository = MovieRepository.getsInstance(application);
}
public LiveData<List<UpcomingMovies>> getUpcomingMovies() {
mUpcomingMovies = movieRepository.getUpcomingMovies();
return mUpcomingMovies;
}
还有我的存储库方法
public LiveData<List<UpcomingMovies>> getUpcomingMovies(){
if(movieDao.loadUpcomingMovies().getValue() == null) {
webService.getUpcomingMovies(api_key).
enqueue(new Callback<MovieResults>() {
@Override
public void onResponse(Call<MovieResults> call, Response<MovieResults> response) {
MovieResults results = response.body();
if(results == null) return;
new insertAsyncTask(movieDao).execute(results.movies.toArray(new Movie[results.movies.size()]));
}
@Override
public void onFailure(Call<MovieResults> call, Throwable t) {
Log.d("Retrofit error", t.getMessage());
}
});
}
return movieDao.loadUpcomingMovies();
}
private static class insertAsyncTask extends AsyncTask<Movie, Void, Void> {
private final MovieDao mAsyncTask;
insertAsyncTask(MovieDao dao){
mAsyncTask = dao;
}
@Override
protected Void doInBackground(Movie... movies) {
long [] results = mAsyncTask.insertMovies(Arrays.asList(movies));
long [] results2 = mAsyncTask.insertUpcomingMovies(Arrays.asList(movies));
return null;
}
}
results
和results2
都返回20个数字,我将其归因于我收到了20部电影。
我在这里做错了什么?感谢您的时间
答案 0 :(得分:1)
实施LifeCyclebserver来查看模型并将其添加到您的活动中:
getLifecycle().addObserver(viewModel);
答案 1 :(得分:0)
请记住,您的viewModel需要有一个不带任何参数的构造函数