1

I am using the DownloadManager to download files and would like to update a progress view in a RecyclerView.ViewHolder for each download.

My current idea is to use Otto to post a downloadProgressed event. I would like my viewHolders to register in the event bus, but I am not sure where I should have them register and unregister.

Is this a good idea? Or should I be looking for a better solution?

Hackmodford
  • 3,901
  • 4
  • 35
  • 78
  • IIRC, viewholders are recycled every time a scroll event happens. So I don't think it is a good idea to change anything inside it. For me, I would subscribe to Otto in the fragment/activity that holds the adapter and call `notifyItemChanged(position)` from there. – emen May 24 '16 at 02:55
  • Sounds like I would have to use a for loop each time my download progressed to find the position. Is that as efficient as just responding to an event and making sure the item matches before changing the progress view? I only need to register for events when the viewholder us created, not when data has been bound. I just can't find a good place to deregister. – Hackmodford May 24 '16 at 03:15

2 Answers2

0

You can register the event bus in the fragment/activity and pass events to your adapter through a funciton.

Your subsciber in the fragment/activity will look like this

@Subscribe public void downloadEvent(DownloadEvent event){
    adapter.updateDownloadState(event.getItemId(), event.getDownloadProgressPercentage());
}

Inside your adapter have a function like this

public void updateDownloadState(int itemId, int progress){
    Object obj = findItemWithId(itemId);
    obj.setProgress(progress);
    this.notifyDataSetChanged();
}

private Object findItemWithId(int itemId){
    // code to find your object in the list eg. by iteration
}
Bubunyo Nyavor
  • 2,511
  • 24
  • 36
0

You should not bind the ViewHolders. The purpose of the ViewHolder is to bind the data in the Adapter to the Views. You should update the data in the Adapter and call notifyItemChanged(index). You most likely should not be worried about performance unless you are running into measurable performance issues.

If you are worried about performance.

  1. First implement a clean solution (premature-optimization is very very bad).

  2. Measure your performance issues.

  3. Optimize (e.g. cache the index of each download in the adapter) and compare the performance with your measured value.

cyroxis
  • 3,661
  • 22
  • 37