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

查看:120
本文介绍了使用 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.

我可以在 BindViewHolder 上添加观察者,但我不明白什么时候应该删除观察者

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天全站免登陆