Last active
September 9, 2019 23:12
-
-
Save mitchtabian/fac3402a4f22f2b291278d5df262491f to your computer and use it in GitHub Desktop.
DiffUtil example: https://developer.android.com/reference/kotlin/androidx/recyclerview/widget/DiffUtil
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BlogItemDiffCallback( | |
var oldBlogList: List<BlogPost>, | |
var newBlogList: List<BlogPost> | |
): DiffUtil.Callback() { | |
override fun areItemsTheSame( | |
oldItemPosition: Int, | |
newItemPosition: Int | |
): Boolean { | |
return (oldBlogList.get(oldItemPosition).pk | |
== newBlogList.get(newItemPosition).pk) | |
} | |
override fun getOldListSize(): Int { | |
return oldBlogList.size | |
} | |
override fun getNewListSize(): Int { | |
return newBlogList.size | |
} | |
override fun areContentsTheSame( | |
oldItemPosition: Int, | |
newItemPosition: Int | |
): Boolean { | |
return (oldBlogList.get(oldItemPosition) | |
== newBlogList.get(newItemPosition)) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun submitList(blogList: List<BlogPost>){ | |
CoroutineScope(Main).launch{ | |
val oldList = items | |
withContext(IO){ | |
val diffResult: DiffUtil.DiffResult = DiffUtil.calculateDiff( | |
BlogItemDiffCallback( | |
oldList, | |
blogList | |
) | |
) | |
withContext(Main){ | |
items = blogList | |
diffResult.dispatchUpdatesTo(this@MainRecyclerAdapter) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment