Lalit Poptani Lalit Poptani - 2 months ago 12
Android Question

GreenRobot: EventBus's isRegistered() method not working as expected

I am using EventBus for receiving the events. I want to check if my Activity is already registered or not as I need to register only once through the whole lifetime of the application, but the issue is that wheneven I come to that Activity which is registered EventBus registers it again and due to that multiple events are getting fired.

Below is my code sample!

public void registerEventBus(){
if(EventBus.getDefault().isRegistered(this)){
Log.e(TAG, "already registered event bus for "+TAG);
}
else{
EventBus.getDefault().register(this);
Log.e(TAG, "registering event bus for "+TAG);
}
}


Also, find the screenshot of logs, in which you can see that initially it gives me proper response but once I move to that Activity again it registers the subscriber again!

NOTE: Please don't suggest me to unregister as I want it to be registered always!

enter image description here

answered on github as well - https://github.com/greenrobot/EventBus/issues/355

Answer

If your Activity is destroyed and recreated (eg during rotation), then a new instance of your Activity will be registered with EventBus.

If you don't unregister the old instance during a corresponding exit point (onPause/onStop/onDestroy), then an event will be sent to both Activities.

To confirm change your log to

Log.e(TAG, "already registered event bus for " + this);
Comments