Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 601
Lalit Poptani Avatar asked Nov 18 '25 15:11

Lalit Poptani


1 Answers

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);
like image 112
William Avatar answered Nov 20 '25 04:11

William



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!