Hundreds of Items in a RecyclerView - Part 2

DZone 's Guide to

Hundreds of Items in a RecyclerView - Part 2

In Part 2, we revisit the RecyclerView structure we discussed last time and explore how to make performance optimizations.

· Mobile Zone ·
Free Resource

In Part 1, we talked about the general structure and how it would allow us to display a large amount of content in the RecyclerView without paging or streaming. In this part, we will revisit this structure to see if we can do better.

What we can do is to only store IDs in the RecyclerView’s adapter, and load each JokePreview as demanded.

class JokeAdapter extends RecyclerView.Adapter<JokeViewHolder> {
  List<Integer> jokesIds;
  JokeService jokeService;
  // other attributes.

And at the ViewHolder binding:

public void onBindViewHolder(JokeViewHolder viewHolder, int position) {
  int jokeId = jokesIds.get(position);

When I tested this on a very old device (released in 2013), it was very quick I couldn’t even notice a glitch. But we can do better.

The next step is to have a cache in the JokeService that will allow us to reduce the database queries.

So, in the JokeService, I used Android’s LruCache:

LruCache<Integer, Maybe<JokePreview>> previews = new LruCache<>(200);
Maybe<JokePreview> previewById(int id) {
  Maybe<JokePreview> preview = previews.get(valueOf(id));
  if (preview != null) {
  return preview;

  Maybe<JokePreview> newPreview = jokeRepository.previewById(id).cache();
  previews.put(valueOf(id), newPreview);
  return newPreview;

Notice here that we have to cache the resulted Maybe from the repository; otherwise, we will just keep hitting the database each time there is a new subscription.

This works perfectly and it was so smooth to scroll. You can try these techniques on this app.

If you notice carefully, we still can do one more optimization where we won’t need any pagination at all. Instead of storing the IDs in the Adapter, what if we came up with a way to generate the value of the IDs? Then we could have an infinite amount of data in the RecyclerView.

android ,memory consumption ,mobile ,mobile app development ,performance ,recyclerview

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}