NotifyDataSetChanged- RecyclerView - 是异步调用吗? [英] NotifyDataSetChanged- RecyclerView -Is it an asynchronous call?

查看:21
本文介绍了NotifyDataSetChanged- RecyclerView - 是异步调用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在回收视图上执行 notifyDataSetChanged 后遵循一组语句.但是当我调试我的应用程序时,调试器会在我的 notifyDataSetChanged 之后到达接下来的几行,然后再转到 recyclerview 的适配器的 onBindViewHolder.所以我的问题是 - notifyDataSetChanged 是异步调用吗?如果是,我们会收到回调吗?PS:我已经在谷歌上搜索了这个答案,但找不到合适的答案,这就是我向社区提问的原因.

I am trying to follow a set of statements after the execution of notifyDataSetChanged on a recyclerview. But when I am debugging my application, the debugger reaches the next few lines after my notifyDataSetChanged before going to the onBindViewHolder of the recyclerview's adapter. So my question is- Is the notifyDataSetChanged an asynchronous call? If yes do we get a callback? PS: I have already googled this answer and I couldn't find a suitable answer that's why I am asking the community.

推荐答案

Recycler在这里查看作者,

RecyclerView author here,

当您调用 notifyDataSetChanged 时,RecyclerView 会使数据无效,但直到下一个动画帧才会更新 UI.这就是 android 视图系统的工作原理.当小部件失效(例如更改其数据)时,它请求布局,这意味着它将在下一次视图遍历中重新测量和重新布局.这样做是为了我们可以批量更改所有更改,直到下一次屏幕更新.这就是 notifyDataSetChange 不会立即触发 onBind 的原因.

When you call notifyDataSetChanged, RecyclerView invalidates the data but does not update the UI until the next animation frame. This is how android view system works. When a widget is invalidated (e.g. changing its data) it requests a layout which means it will be re-measured and re-laid out in the next view traversal. This is done so that we can batch all changes until the next time screen will be updated. This is why notifyDataSetChange does not trigger an onBind instantly.

是的,您可以将其称为异步调用,但这并不意味着您可以多线程运行它(这是两个完全不同的概念).您仍然必须在主线程上对适配器进行所有更改.当你改变适配器时,你必须立即通知 RecyclerView,这就是为什么通知也必须在主线程上.

So yes, you can call this as an async call but that does not mean that you can run it multi-threaded (these are two totally different concepts). You still have to make all changes to your adapter on the main thread. When you change the adapter, you have to notify RecyclerView instantly, which is why notify also has to be on the main thread.

这个限制的原因是如果数据集在布局过程中发生变化,布局管理器很难恢复到稳定状态(例如想象 RecyclerView 调用 onBind(5)并且同时在另一个线程中删除了第 5 项).此外,考虑到这些变化将需要大量的同步,这将是一个很大的性能损失,没有任何好处.这就是为什么所有 UI 组件都是单线程的.

The reason for this limitation is that if the data set is changed during a layout, it is very hard for the layout manager to recover to a stable state (e.g. imagine RecyclerView calls onBind(5) and item 5 is removed in another thread at the same time). Also, accounting for such changes will require a lot of synchronization which will be a big performance penalty without any benefit. This is why all UI components are single threaded.

这篇关于NotifyDataSetChanged- RecyclerView - 是异步调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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