LiveData setValue 应该触发了 Activity 中的 onChanged 方法,但是它只在第一次调用,当我尝试进行分页之后,它会中断并且不再调用 onChanged,尽管我的响应确实成功并且我看到它在日志。setValue/postValue 有什么问题?它是一个错误吗?我应该自己实现观察者模式吗?那么使用 LiveData 有什么意义呢?我的寻呼仅在这 2-3 天后不起作用.....
MainActivity 类
public class MainActivity extends AppCompatActivity private MutableLiveData<List<Photo>> mLivePhotos; // some code... @Override protected void onCreate(Bundle savedInstanceState) { mLivePhotos = loadData(); mLivePhotos.observe(this, photos -> { Log.d(TAG, "onChanged!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); mProgressBar.setVisibility(View.GONE); mPhotos = photos; if (mIsInitialCall) { initiateAdapter(); mIsInitialCall = false; } else { mAdapter.updateList(mPhotos.subList(mPageNumber, mPageNumber + 10)); } }); mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { int lastPosition = mLayoutManager.findLastCompletelyVisibleItemPosition(); Log.d(TAG, "onScrolled - lastPosition: " + lastPosition); if (lastPosition == mLayoutManager.getItemCount() - 1) { Log.d(TAG, "onScrolled - End of list?"); loadData(); } } }); } private MutableLiveData<List<Photo>> loadData() { Log.d(TAG, "loadData"); if (mArticleViewModel == null) return null; mPageNumber += 10; mProgressBar.setVisibility(View.VISIBLE); return mArticleViewModel.loadPhotos(); }
视图模型
public class ArticleViewModel extends ViewModel { private MutableLiveData<List<Photo>> photos; private ArticleRepository articleRepository; public MutableLiveData<List<Photo>> loadPhotos() { Log.d(TAG, "getArticleList"); //TODO; add Dagger 2 articleRepository = new ArticleRepository(); photos = articleRepository.getPhotos(); return photos; }
存储库
public class ArticleRepository { public MutableLiveData<List<Photo>> getPhotos() { final MutableLiveData<List<Photo>> result = new MutableLiveData<>(); Log.d(TAG, "getResults"); ApiService.getService().getPhotos().enqueue(new Callback<List<Photo>>() { @Override public void onResponse(Call<List<Photo>> call, Response<List<Photo>> response) { Log.d(TAG, "onResponse"); if (response.isSuccessful()) { Log.d(TAG, "isSuccessful"); result.postValue(response.body()); } } @Override public void onFailure(Call<List<Photo>> call, Throwable t) { Log.d(TAG, "onFailure: " + t.getMessage() + "\n" + t.getStackTrace()); } }); return result; }