update RecyclerView with Android LiveData

前端 未结 4 1007
感动是毒
感动是毒 2021-01-31 16:13

There are many examples how to push new list to adapter on LiveData change.

I\'m trying to update one row (e.g number of comments for post) in the huge list. It would be

4条回答
  •  面向向阳花
    2021-01-31 16:46

    Like @Lyla said, you should observe the whole list as LiveData in Fragment or Activity, when receive changes, you should set the whole list to the adapter by DiffUtil.

    Fake code:

    PostViewModel {
        LiveData> posts;  // posts comes from DAO or Webservice
    }
    
    MyFragment extends LifecycleFragment {
        PostAdapter postAdapter;
    
        ...
    
        void onActivityCreated() {
            ...
            postViewModel.posts.observer(this, (postList) -> {
                postAdapter.setPosts(postList);
            }
        }       
    }
    
    PostAdapter {
        void setPosts(List postList) {
            DiffUtil.DiffResult result = DiffUtil.calculateDiff(new DiffUtil.Callback() {...}
            ...
        }
    }
    

提交回复
热议问题