使用Android LiveData更新RecyclerView [英] update RecyclerView with Android LiveData

查看:1729
本文介绍了使用Android LiveData更新RecyclerView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多示例,如何在LiveData更改时将新列表推送到适配器.

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 stupid to reset whole list to change only one field.

我可以在onBindViewHolder上添加观察者,但我不知道何时删除观察者

I am able to add observer onBindViewHolder, but I can't understand when should I remove observer

@Override
public void onBindViewHolder(ViewHolder vh, int position) {
    Post post = getPost(position);
    vh.itemView.setTag(post);
    post.getLiveName().observeForever(vh.nameObserver);
    ... 
}

推荐答案

就像@Lyla所说,您应该在Fragment或Activity中将整个列表作为LiveData进行观察,当接收到更改时,应该通过DiffUtil将整个列表设置为适配器

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.

伪造代码:

PostViewModel {
    LiveData<List<Post>> 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<Post> postList) {
        DiffUtil.DiffResult result = DiffUtil.calculateDiff(new DiffUtil.Callback() {...}
        ...
    }
}

这篇关于使用Android LiveData更新RecyclerView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆