从MutableLiveData更改数据时无法触发onChange

时间:2018-05-13 18:05:11

标签: android android-livedata

我有一个MovieRepository使用Retrofit检索JSON,它负责此应用程序中使用的所有数据,这是单一的事实来源。然后,我有MainActivityViewModel使用MovieRepository,它负责向UI层提供数据。

MainActivity内部,我有一个菜单选项:Most popularTop rated option,当用户点按它时,我想更改为用户界面。这是我的方法:

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case R.id.top_rated_menu:
            viewModel.getMovie(MovieAPIUtils.Endpoints.TOP_RATED_ENDPOINT);
            return true;

        case R.id.most_popular_menu:
            viewModel.getMovie(MovieAPIUtils.Endpoints.POPULAR_ENDPOINT);
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

视图模型中的getMovie()方法是:

public class MainActivityMovieViewModel extends ViewModel {

    private static final String TAG = MainActivityMovieViewModel.class.getSimpleName();

    private MutableLiveData<ReturnMovie> movie;
    private MovieRepository repo = new MovieRepository();
    private String search = null;

    public LiveData<ReturnMovie> getMovie(String searchTerm) {

       if (movie == null) {
           movie = repo.search(searchTerm);
       }
        return movie;
    }
}

这是我的存储库:

public class MovieRepository {

    private static final String TAG = MovieRepository.class.getSimpleName();

    public MutableLiveData<ReturnMovie> search(final String term) {
        final MutableLiveData<ReturnMovie> data = new MutableLiveData<>();

        MovieService service = ServiceGenerator.createService(MovieService.class);
        Call<ReturnMovie> call = service.requestMovie(term, MovieAPIUtils.KEY);

        call.enqueue(new Callback<ReturnMovie>() {
            @Override
            public void onResponse(Call<ReturnMovie> call, Response<ReturnMovie> response) {
                ReturnMovie movie = response.body();
                data.setValue(movie);
            }
            @Override
            public void onFailure(Call<ReturnMovie> call, Throwable t) {
                Log.d(TAG, t.toString());
            }
        });
        return data;
    }
}

出于某种原因,当调用viewModel.getMovie()时,onChange中的LiveData方法未被触发,我尝试阅读Android架构上的文档并尝试了不同的方法,但仍然失败。

以下是我在MainActivity中的OnCreate()

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    viewModel = ViewModelProviders.of(this).get(MainActivityMovieViewModel.class);
    initRecyclerViewWithMovies();

    final Observer<ReturnMovie> observer = new Observer<ReturnMovie>() {
        @Override
        public void onChanged(@Nullable ReturnMovie returnMovie) {
            mMovieAdapter.swapCursor(returnMovie.getResults());
        }
    };

    viewModel.getMovie(MovieAPIUtils.Endpoints.POPULAR_ENDPOINT)
            .observe(this, observer);
}

完整代码:

https://github.com/brendoncheung/PopularMovie/tree/mvvm_approach

非常感谢!

0 个答案:

没有答案