Search code examples
androidpicassorace-condition

How to cancel picasso requests for specific view?


Currently I have something along the lines of this

public class SomeActivity extends AppCompatActivity
{
    public AppCompatImageView myFavPicture;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_some);

        myFavPicture = (AppCompatImageView) findViewById(R.id.my_fav_picture);
    }

    public void setPictureToRed()
    {
        myFavPicture.setImageResource(R.color.red);
    }

    public void setPictureToLink(Uri link)
    {
        Picasso.with(this).load(link).into(myFavPicture);
    }
}

The problem I currently have is the worry that is one concerning race conditions between setPictureToRed and setPictureToLink

If I call setPictureToLink(someLink) and then immediately call setPictureToRed before picasso can fully load the image - I am afraid that picasso will come back later and overwrite the red picture (which is not what I want)

Is there some way to do something like this?

public void setPictureToRed()
{
    // flush all previous loads for "myFavPicture" to avoid race conditions
    Picasso.with(this).flush(myFavPicture);
    myFavPicture.setImageResource(R.color.red);
}

Solution

  • Picasso.with(this).cancelRequest(myFavPicture);
    myFavPicture.setImageDrawable(null);
    myFavPicture.setImageResource(R.color.red);