Sunday, 29 September 2013

Using a WeakReferenced listener

Using a WeakReferenced listener

Assuming the following:
public interface Listener {
public void onListen();
}
public class ActionClass {
WeakReference<Listener> listener = null;
public void doAction(String action, Listener listener) {
this.listener = new WeakReference<Listener>(listener);
doTheAction(action);
}
public void actionComplete() {
if (listener != null && listener.get() != null)
listener.onListen();
}
}
public class AnotherClass {
ActionClass actioner = new ActionClass();
void init() {
actioner.doAction("something", new Listener() {
onListened() {
Log.d("Tag", "Action complete!");
}
};
}
}
Sorry if there are typos/syntax errors, this was more meant to be pseudo
code.
Anyway, a lot of times by the time the "Action" is complete, the
WeakReference to listener will be GCed, even though the instance of
"AnotherClass" is still alive. Is there a way to avoid this?

No comments:

Post a Comment