What are the disadvantages of Eventbus subscription in Application class?

I use EventBus in my Android app. Is it a good idea to make Eventbus.getDefault().register(this) in my Application.onCreate() ? I do not have user interface updates. I am trying to do this to make sure I get subscription data even if the application goes into the background. There may be other ways to achieve what I want, but I am curious if something is wrong with this approach.

My doubts:

  • Will this cause some kind of memory leak? Eventbus refers to the Application object, and the Application object also relies on the Eventbus. It looks cyclical.

  • When do I need to unregister? Application.onTerminate () is not guaranteed. If # 1 is not a problem, I think it's fine to ignore unsubscribing in the Application class.

+4
source share
2 answers

Will this cause a memory leak? Eventbus refers to the Application Object and the application object also relies on Eventbus. It looks cyclical.

It is perfectly normal to subscribe to events directly from the Application class. The OS will clear the application, and EventBus is part of this. No problems.

When do I need to unregister? Application.onTerminate () is not guaranteed to be called. If # 1 is not a problem, I think it's fine to ignore unsubscribing in the Application class.

Yes, I would also unsubscribe from Terminate, just for completeness. But you are right on the Android device, if the application is cleaned, then everything just left, so there is no need to "clear".

+5
source

The application class will be killed when the application physically stops.

It means:

  • When the OS decides to physically terminate the application (maybe it can be days for this) or there is external intervention (i.e. the user stops it or the utility application, for example, Clean Master), the application will be completely stopped and destroyed.
  • Any static links will also be deleted from memory (i.e. one single-point EventBus).

(2) will be valid only if you properly unregister your listeners, i.e. unregister activity / fragment when you stop or unregister when View.onDetachedFromWindow () , etc.

Until you try to run something in a separate thread in your callback method or update a non-existent object / view / fragment, you should be fine.

0
source

All Articles