Soheil
Soheil

Reputation: 627

android-Picasso callback prevents garbage collecting

I use Picasso library in my android app to load images. I need to get notified when the image is loaded successfully, so I use:

Picasso.get().load(imageURL).into(imageView, new Callback() {
        @Override
        public void onSuccess() {
            // do sth
        }

        @Override
        public void onError(Exception e) {

        }
    });

as it is mentioned in Picasso library documentation, The Callback param is a strong reference and will prevent your Activity or Fragment from being garbage collected. due to this reason, the memory used by my app grows so much after replacing a number of fragments-which all use the callback.

how to get rid of the callback and allow the fragments to be garbage collected after onSuccess method has been run?

Upvotes: 0

Views: 106

Answers (1)

sajjad
sajjad

Reputation: 847

Add a tag when using Picasso:

        Picasso.get().load("imageURL").tag("custom_tag").into(imageView, new Callback() {
        @Override
        public void onSuccess() {
            // do sth
        }

        @Override
        public void onError(Exception e) {

        }
    });

And then before replacing/removing your fragment or quitting your activity, cancel the task by calling:

Picasso.get().cancelTag("custom_tag");

Note that the callback will automatically be removed after onSuccess() is called. So the offered solution is useful when the callback has not yet fulfilled.

Upvotes: 1

Related Questions