Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

android - NotifyDataSetChanged- RecyclerView -Is it an asynchronous call?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

RecyclerView author here,

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...