1. 程式人生 > >DiffUtil is a must!

DiffUtil is a must!

DiffUtil is a must!

First arrival of new data for your empty RecyclerView.Adapter is trivial, just consume the event and you are all set. I’ve spent a lot of time finding less hassle ways to trigger updates when new data arrives when my adapter is not empty. I had to look for ranges and indices and what not, many iterations for nothing.

As of 24.2.0, RecyclerView support library, v7 package offers really handy class called DiffUtil. It’s a life saver, it saves you from torments and hell of ranges and indices.

Code, pls.

DiffUtil needs to fetch most basic details about your two lists, like the size and basic item comparison. DiffUtil.Callback

is used to provide DiffUtil with the basic information of the lists we are going to compare.

For my next trick I’m going to use simple Product model for my Adapter.

Yas! That’s the Callback

Callback is an abstract class and needs to override methods about the sizes of the two lists and the comparison for items at particular index. I’m not familiar with the internal implementation, I had to add null checks (and left out some) just for sure. Of course, lists can be of any type, generifying the Callback

will only deepens the comparisons of the items.

You may notice the getChangePayload() method, which is not abstract. This method is called when the areItemsTheSame() returns true, but areContentsTheSame() returns false, which means that we are talking about the same item but the fields data might have changed. Basically, this method returns the reason(s) why there is a difference in the lists.

In this, I used a Bundle to return more than one reason about the changes which make the compared items content not the same.

Once we have the callback, it is pretty easy.

@ Override
public void onNewProducts(List<Product> newProducts) {
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new ProductListDiffCallback(mProducts, newProducts));
diffResult.dispatchUpdatesTo(mProductAdapter);

}

DiffResult object that is returned from diff calculation, dispatches the changes to the Adapter, if any.

Payloads

Object returned in getChangePayload() is dispatched from DiffResult using notifyItemRangeChanged(position, count, payload), upon which is called Adapter’s onBindViewHolder(… List<Object> payloads) method.

@Override
public void onBindViewHolder(ProductViewHolder holder, int position, List<Object> payloads) {
if(payloads.isEmpty()) return;
else{
Bundle o = (Bundle) payloads.get(0);
for (String key : o.keySet()) {
if(key.equals(KEY_DISCOUNT)){
//TODO lets update blink discount textView :)
}else if(key.equals(KEY_PRICE)){
//TODO lets update and change price color for some time
}else if(key.equals(KEY_REVIEWS_COUNT)){
//TODO just update the review count textview
}
}
}
}

Huge lists

Documentation suggests that DiffUtil might take some time for large data sets and it is advised to move the calculation to background thread. Here is tiny RxJava example:

Dispatching the DiffResult to main thread:

@Override
public void onNext(DiffUtil.DiffResult result) {
result.dispatchUpdatesTo(mProductAdapter);
}

Conclusion:

DiffUtil calculates the difference between two given lists, the old list that is currently displayed and the new that you have recently obtained. The DiffResult contains the data updates that can be dispatched to your adapter.

相關推薦

DiffUtil is a must!

DiffUtil is a must!First arrival of new data for your empty RecyclerView.Adapter is trivial, just consume the event and you are all set. I’ve spent a lot o

is-a

所在 調用 pan family 內存 傳遞 既然 通過 end -----------------siwuxie095 is-a 在 C++ 中,is-a (是一個)的概念就相當於 隱形眼鏡也是眼鏡

[uvalive 7263] Today Is a Rainy Day(暴力,BFS,dp)

預處理 ini pen sta 現在 修改 ace printf main 題目鏈接:https://vjudge.net/problem/UVALive-7263 題意:給兩個字符串a,b,只包含1~6的數字,現在允許兩種操作:1、修改某一位數字,2、修改整個串的某個數字

假設寫一段代碼引導PC開機這段代碼是 ? Here is a tiny &quot;OS&quot; :-D

博士 輸出 虛擬 mov download 開機 控制 style blog Hello world -- OS 我找到了華科紹誌遠博士的相關代碼,發現他依據MIT的JOS的boot.S 稍作改動。然

freedom is a kind of responsibility

重寫 小學 三個月 一個 經濟 創新 裏的 它的 整形 張維迎教授在2017年7月1日北大國發院2017屆畢業典禮上的發言《自由是一種責任》 張維迎:自由是一種責任 本文為張維迎教授在2017年7月1日北大國發院2017屆畢業典禮上的發言 同學們好!首先祝賀大

UVALive - 7263 Today Is a Rainy Day(bfs)

二次 變換 net -- bfs math font 字符串 print 原題鏈接 題意 給兩個等長的只含數字1,2,3,4,5,6的字符串s(|s|≤110),有兩種操作: - 把一個位置的數字換成另一個數字,換成的數字也只能是1到6- 把這個字符串中相

Coursera Algorithms week4 基礎標簽表 練習測驗:Check if a binary tree is a BST

eth rmi tree eterm left div mine ont ret 題目原文: Given a binary tree where each ???????? contains a key, determine whether it is a binary

Expected MultipartHttpServletRequest: is a MultipartResolver configured?

XML red commons param 方法 ng- rop dsi ring 解決方法: (1) 第一步:引入commons-fileupload-1.2.jar,具體版本號以具體項目要求為準; 第二步:在spring-mvc.xml中增加如下配置,具體文體大小限制以

Two Sum IV - Input is a BST

empty rip nta 一個 con bool earch arch there Given a Binary Search Tree and a target number, return true if there exist two elements in th

[LeetCode] Two Sum IV - Input is a BST 兩數之和之四 - 輸入是二叉搜索樹

count imp itl .com 否則 href 當前 recursive 兩數之和 Given a Binary Search Tree and a target number, return true if there exist two elements i

what-is-a-closure

arc quest draft overflow targe .com com http www. https://stackoverflow.com/questions/36636/what-is-a-closure http://www.cs.tufts.edu/~n

653. Two Sum IV - Input is a BST

span div targe public || style contains there lean Given a Binary Search Tree and a target number, return true if there exist two element

win10 安裝nodejs,報錯there is a problem in the windows installer package

nload 裝包 ack next org get 就是 技術分享 提示符 1. 在開始面板找到命令提示符,右鍵選擇“以管理員身份運行” 2. 進入到安裝包的文件目錄內 3. 回到命令提示符窗口,運行安裝包名字 之後會跳出安裝提示,點擊運行 之後就一直next,就

新手使用Vector報錯Vector is a raw type. References to ge

str parameter 了解 不能 我不 raw reference ner 新手 照著書上抄代碼有下面一句private Vector vector=null;但是eclipse報錯Vector is a raw type. References to generic

JAVA基礎——is-a 、have-a、和 like-a的區別

就是 不同類 alike 不同 pc機 空調 面向 們的 合成 1、is-a,has-a,like-a是什麽 在面向對象設計的領域裏,有若幹種設計思路,主要有如下三種: is-a、has-a、like-a java中在類、接口、抽象類中有很多體現。 了解java看這裏:什麽

This is a bug I believe, and it took me 2-3 days to figure it out. Please do the following to get it working,

this nco etc figure ood client clas gpo see This is a bug I believe, and it took me 2-3 days to figure it out. Please do the following to

spring-boot 啟動時候 出現異常:The bean 'xxx' could not be injected as a 'xx.xxxx' because it is a JDK dynamic proxy that implements:

ng- for sed AC 存在 cti 解決方法 sid 失敗 The bean ‘xxxService‘ could not be injected as a ‘AaaXxxService‘ because it is a JDK dynamic proxy tha

net.sf.json.JSONException: There is a cycle in the hierarchy!

遞歸 組裝 set mil 對象 數組 tail csdn 都沒有 轉自:https://blog.csdn.net/waysoflife/article/details/24351051 原因分析: 這個異常是由於JSONObject插件內部會無限拆解你傳入的對象,直

What is a shell and what is Bash?

space import span process ext 屏蔽 解釋器 ffffff shadow 常聽說:shell編程,Bash編程,和Bash shell編程,究竟什麽是shell,又何為Bash,兩者有什麽聯系…簡單的說,shell是命令解釋器,用於解析和執行命令

[leetcode]653. Two Sum IV - Input is a BST

oar array 們的 func 通過 fun number lee inpu Given a Binary Search Tree and a target number, return true if there exist two elements in the B