Question

Say that I have a singleton class (Downloader) responsible for downloading and persisting files. When a client requests a download, he must also provide a callback. My question regards the storage of those callback objects.

If I have an Activity that implements the callback interface and then requests multiple large downloads, the Downloader class will hold a reference to the Activity indefinitely. What if before the downloads are finished the Activity that requested them goes through its life-cycle and is destroyed.

In this case the Downloader will prevent the recycler from garbage collecting the Activity. I don't mind that the requested downloads continue. What I would like to do however, is somehow detect that the callback provided should be collected and I am effectively leaking it.

Is there a design pattern for something like this? I was thinking that one of the Reference subclasses would be useful.

Thanks.

Was it helpful?

Solution

Do it the other way around and you can keep them disconnected and avoid the highly unrecommended practice of keeping activity references around.

I created a very simple ServiceLocator class that keeps static references to all of my singletons and resolves them by type, but you can do this even simpler. You just need a class that holds a static reference to your Downloader and exposes that reference to your activities. If you need to call back into any of your activities, use the publish/subscribe model that the Android framework does (i.e. setOnClickListener(OnClickListener listener)).

Downloader can have an inner interface called DownloadUpdateListener, a single instance of this interface, and a register and unregister method for setting this and removing the reference from your activities. The Activity will create an instance of it DownloadUpdateListener locally so it has access to all of the Activity's fields and views. In Downloader, check that your listener isn't null before calling its methods. Register your listener in onResume and don't forget to unregister it in onPause

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top