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

2

9

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.

Vertu answered 3/8, 2015 at 23:40 Comment(0)
D
9

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'.

Devito answered 26/2, 2016 at 17:7 Comment(0)
A
0

Your Application class will be killed when the app physically stops.

Which means:

  1. When the OS decides do stop physically the app (could be days for this to happen) or there is an external intervention (i.e. user stops it or a utility app like Clean Master does it), the app will be completely stopped and destroyed.
  2. Any static references will be removed from the memory too (i.e. your EventBus singleton one).

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

As long in your event callback method you are not trying to run something in a separate thread or update a non-existing activity/view/fragment, you should be fine.

Ashore answered 20/11, 2015 at 23:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.