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

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

问题描述

我试图在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.

推荐答案

此处为RecyclerView作者,

RecyclerView author here,

调用notifyDataSetChanged时,RecyclerView使数据无效,但直到下一个动画帧才更新UI.这就是android view system的工作方式.当小部件失效(例如更改其数据)时,它会请求布局,这意味着将对其进行重新测量并在下一次视图遍历中对其进行重新布局.这样做是为了让我们可以批量处理所有更改,直到下次屏幕更新为止.这就是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,这就是为什么notify也必须位于主线程上的原因.

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