Don’t have to release RecyclerView’s ViewHolder

Jieyi Wu
2 min readJan 16, 2018

--

This article is about what I faced a big issue I couldn’t fix it smoothly. I spent a whole day finding this problem. Hope my experience could help who is facing the same problem with me.

Issue

I’m using MVVM architecture for developing my side project. I think I should follow this architecture’s concept in whole app, including activity, fragment, service, recyclerview, …, etc.

In this app, I use recyclerview massively, we can see it in the most of the fragments XD because it easy to show a big data to a user.

In my architecture, each of the items of the recyclerview has a holder which is ViewModel. My code will be as below:

The adapter, I did encapsulate and separate the ViewHolder from the adapter. When the adapter is initiated the ViewModels will be created one by one at the meantime.

There are few problems

  1. The ViewModels will keep creating until the fragment/activity’s lifecycle finishes. i.e. there will be unlimited ViewModels. It also causes Memory Leak!
  2. The action’s result in the ViewModels will be unexpected.
  3. If we register some objects in a ViewModel, it couldn’t be unregister.
  4. The items couldn’t be recycled. The reason comes from 1.

Let’s solve this critical bug!

First, we have to understand the items of the recyclerview are recyclability! The same as the word XD

That’s why we don’t need to release or unregister them on detach time or some functions. The system(SDK) will help us to finish it. If you really need to do it (as like me).

My way is that keeping each ViewModel to a list container. When the lifecycle of the activity/fragment which the RecyclerView attached is finished, we run all ViewModels in the list container to do the detach action.

My code is as below:

I google a lot of the articles about how to detach or unregister the ViewHolders, I didn’t find who faces kind of the problem with me, until I found Jake Wharton’s response to a person faces the similar problem in his RecyclerView.

The link is here!

I just share a method what I could think 😞. If you have any better way to solve similar with this. Please don’t be shy to share to me 🙂

--

--