MVVM和RecyclerView和LiveData

时间:2018-03-22 14:52:57

标签: android mvvm android-recyclerview android-room android-livedata

我尝试使用MVVM approach在片段中实施RecyclerView,但我在第一次加载时刷新其内容时遇到问题,如下是我跟随的步骤:

  1. 我创建了RecyclerView
  2. 在其上设置自定义适配器

     recyclerView.setAdapter(adapter);
    
  3. 订阅我的模型上的通知(使用Room完成的持久层)

     viewModel.getVideosForCategoryId(category.getId()).observe(this,
     videos -> {
         if (videos.size() > 0) {
             long catId = videos.get(0).getIdCategory();
            if (videosListAdapters.containsKey(catId)) {
                videosListAdapters.get(catId).updateList(videos);
            }
         }
    });
    
  4. 通过AsyncListDiffer更新RecyclerView,如here

    所示
    public void updateList(List<Video> newList) {
        differ.submitList(newList);
    }
    
  5. 然而,当第一次调用Observer时,数据存在 videos.size() > 0并通过updateList(videos)传递给RecyclerView,但回收者视图并没有。 t刷新自身并且不调用来自AsyncListDiffer的回调:

            @Override
            public boolean areItemsTheSame(
                @NonNull Video oldUser, @NonNull Video newUser) {
                // User properties may have changed if reloaded from the DB, but ID is fixed
                return oldUser.getIdVideo() == newUser.getIdVideo();
            }
    
            @Override
            public boolean areContentsTheSame(
                @NonNull Video oldUser, @NonNull Video newUser) {
                // NOTE: if you use equals, your object must properly override Object#equals()
                // Incorrectly returning false here will result in too many animations.
                return oldUser.equals(newUser);
            }
    

    感谢您的帮助

0 个答案:

没有答案