Why do I need to put ViewHolder instances in an HashMap?


#1

Hi all,
I’m in trouble with the logic behind this:
When we call the queueThumbnail method from the ViewAdapter, we pass the ViewHolder instance and the url of the image to be downloaded, than we put those items in an hashmap(viewholder,url), so we can get the url easily from the handleMessage method by doing mRequestMap.get(viewholder).
But how does it work? Since recyclerview recycle its viewholders, we should put duplicate keys into the hashmap! Why this doesn’t happen?


#2

The duplicate keys in the hashmap is done on purpose. It is tricky to understand, but the reason this is done is for ViewHolder reuse in the RecyclerView. As you know, when you’re scrolling and views are going off the screen, the RecyclerView re-uses those views in new positions.

What happens if there is an image request that takes a few seconds but the ViewHolder behind it is scrolled off the screen and changes to a new position? You don’t want to show the wrong image at the new position. That is why we use that HashMap. The HashMap will always point to the correct image for a given view holder. As you scroll, the HashMap is immediately updated with the recycled ViewHodler as the key and the new image url as the value. So, it’s always going to contain the latest image.

Does that make sense?