Suppose the following scenario with classes A,B and an instance of a event bus (It can be the Guava event bus, by Google or the Otto event bus, by Squ.re)
class A{
@Subscribe
public void onSomething(B event){
//do something
}
}
A a = new A();
eventBus.subscribe(a);
eventBus.post(new B());
// onSomething is called, everything ok
a = null;
eventBus.post(new B());
// onSomething is called again
Now, if I run that (only tested with Otto) onSomething
is called 2 times.
¿Will the event bus hold a reference to 'a
' until unregister is called?
And more importantly
¿If for some reason I am unable to determine the moment in which 'a
' will be null, then the event bus will hold a useless reference to the object forever (memory leak)?
The event bus will hold a strong reference always. The answer to both of your questions is yes.
When you set a
to null
above you are only clearing the local reference. Both Guava and Otto maintain a strong reference and require explicit unregistration. You will see the above behavior in both event buses.
I strongly suggest you tie the registration of an object to something other than the clearing of a local reference. The Android activity and fragment lifecycle is an obvious choice and so are things like close
and destroy
-like methods on individual objects.