Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why use WeakReference on android Listeners?

I am working on a large code base, and see in many places this type of code:

public static class RequestCustomData implements View.OnClickListener {
    WeakReference<MainActivity> mainActivity;

    public RequestCustomData(MainActivity activity) {
        mainActivity = new WeakReference<>(activity);
    }

    @Override
    public void onClick(View view) {
        MainActivity activity = mainActivity.get();
        activity.requestCustomData(true, null);
    }
}

I am a bit confused why this is used is so many places? I took a look at this document but it did not clarify well why this type of code is so heavily used on the app I am working on it

https://community.oracle.com/blogs/enicholas/2006/05/04/understanding-weak-references

Anyone can explain me if this is a common pattern? If so, why?

like image 257
gmmo Avatar asked Mar 24 '16 01:03

gmmo


1 Answers

A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory.

The authors of this code most likely wanted to avoid leaking of the Activity context if the RequestCustomData object could outlive the Activity itself.

I recommend Romain Guy's post on this topic as well as several specific cases to avoid:

  • inner classes and leaks
  • threads and leaks
like image 104
szym Avatar answered Sep 20 '22 21:09

szym