LiveData observe() not called
My observer callback is not being called, can you point out what am I doing wrong ? My application is really simple since I'm just testing this architecture
MainActivity code
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 code
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;
}
And my repository method
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;
}
}
Both results
and results2
return 20 numbers, which I attribute it to the fact I receive 20 movies.
What have I done wrong here ? Thanks for ur time
Solution 1:
Implement LifeCyclebserver to viewModel and add this in your activity:
getLifecycle().addObserver(viewModel);