Search code examples
greenrobot-eventbus

What are the disadvantages of subscribing to Eventbus in Application class?


I am using EventBus in my Android application. Is it a good idea to do a Eventbus.getDefault().register(this) in my Application.onCreate() ? I don't have any UI updates to be made. I am trying this to make sure that I receive the subscription data even if the app goes to background. There might be other ways to achieve what I want, but I am curious if anything is wrong with this approach.

My doubts are :

  1. Will this cause some kind of memory leak ? Eventbus is referencing the Application object, and the Application object is also relying on Eventbus. This looks cyclic.

  2. When to unregister ? Application.onTerminate() is not guaranteed to be called. If #1 is not an issue, I guess it's fine to ignore unsubscribe in Application class.


Solution

  • Will this cause some kind of memory leak ? Eventbus is referencing the Application object, and the Application object is also relying on Eventbus. This looks cyclic.

    It's totally fine to subscribe to events straight from the Application class. The OS will clean up the Application and the EventBus is a part of that. No problems.

    When to unregister ? Application.onTerminate() is not guaranteed to be called. If #1 is not an issue, I guess it's fine to ignore unsubscribe in Application class.

    Yes I would unsubscribe onTerminate as well, just for completeness. But you're right on an Android device, if the Application is cleaned up then everything is just gone anyway so there is no need to 'clean up'.