Speed up Your Android RecyclerView Using DiffUtil

Learn how to update the Android RecyclerView using DiffUtil to improve the performance. Also learn how it adds Animation to RecyclerView. By Carlos Mota.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

DiffUtil in Jetpack Compose

Jetpack Compose is a new set of libraries that allow you to develop your UI declaratively. You no longer need to rely on XML and findViewById to set and update a view. You can do everything programmatically using the concepts of state and recomposition.

Note: You can find more information about Jetpack Compose in the Jetpack Compose by Tutorials book or from this video course.

With Compose, you can create a list using LazyColumn:

@Composable
fun Groceries() {
  val groceries = remember { mutableStateOf(getGroceriesList(context)) }
  LazyColumn {
    items(groceries.value) {
      AddGrocery(it)
    }
  }
}
 
@Composable
fun AddGrocery(item: Item) {
  Column {
    Text(
      text = item.content
    )
  }
}

Alternatively, if you want to create a horizontal list, you can use LazyRow.

Jetpack Compose works by recomposition. The redesign happens only for functions with changed content. This has direct improvements on performance since it only redraws views that changed. Due to this, there’s currently no implementation on LazyColumn and LazyRow that works with DiffUtil directly.

Another advantage of DiffUtil is that every time there’s an update on the list, it uses ItemAnimator to create smooth animations, without the need to write additional code.

Although not directly supported out of the box in Compose, the same is possible by using AnimatedVisibility and animating all the views.

Curious about how to implement this? Read the book chapter: Animating Properties Using Compose to learn more.

Where to Go From Here?

Download the completed project files by clicking the Download Materials button at the top or bottom of the tutorial.

Congratulations! You learned how to improve your list’s performance and how to create a smooth update animation when updating its content.

There are a couple of scenarios in which lists can have bad performance. You’ll find a set of examples of this in the Slow Rendering section of the Android documentation. Another solution to overcome this issue is the Paging library, which only loads the information that’s necessary to show on the screen.

In this tutorial, you read a bit about Jetpack Compose. Curious about how to create an app using these new libraries? Follow the Getting Started tutorial to learn more.

If you have any questions or comments, please join the discussion below.