Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

picasso: how to cancel all image requests made in an adapter

as usual we use an adapter to populate a listView. in the adapter we use picasso to load the images. i see that as rows are recycled when loading an image into an target (imageView) picasso will automatically cancel requests for that target.

how does one cancel all of the outstanding requests when leaving the fragment or activity?

like image 900
terry Avatar asked Jul 22 '14 20:07

terry


1 Answers

This answer may come a bit late, but maybe someone still needs it...

Define a ViewHolder which provides a cleanup method:

static class ImageHolder extends RecyclerView.ViewHolder {
    public final ImageView image;

    public ImageHolder(final View itemView) {
        super(itemView);
        image = (ImageView) itemView.findViewById(R.id.image);
    }

    public void cleanup() {
        Picasso.with(image.getContext())
            .cancelRequest(image);
        image.setImageDrawable(null);
    }
}

Implement onViewRecycled() in your adapter:

static class ImageAdapter extends RecyclerView.Adapter<ImageHolder> {

    // ...

    @Override
    public void onViewRecycled(final ImageHolder holder) {
        holder.cleanup();
    }
}

Cancel the Picasso requests when your Fragment's view is destroyed (or whenever you wish):

public class MyFragment extends Fragment {
    private RecyclerView recycler;

    // ...

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        recycler.setAdapter(null); // will trigger the recycling in the adapter
    }
}

RecyclerView.setAdapter(null) will detach all currently added Views and their associated ViewHolders will be recycled.

like image 156
sfera Avatar answered Oct 28 '22 23:10

sfera