Search code examples
androidandroid-recyclerviewotto

Update One Item in RecyclerViewAdapter with Otto


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?


Solution

  • 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
    }