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 :
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.
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.
EventBus is an open-source library for Android and Java using the publisher/subscriber pattern for loose coupling. EventBus enables central communication to decoupled classes with just a few lines of code – simplifying the code, removing dependencies, and speeding up app development.
Often times many activities or fragments will assume events are produced as soon as that component subscribes to the event bus. They'll set a field based on the event, and then proceed to use that field in other lifecycle methods with the assumption that it is not null.
Don't ever use EventBus as a multithreading framework (i.e. for offloading work to background threads). Sticky events can be very handy in some very specific situations, but realize that once you use them, you basically store part of app's state inside the event bus. In most cases, this trade-off isn't justified.
An event bus is a design pattern (and while we'll be talking about JavaScript here, it's a design pattern in any language) that can be used to simplify communications between different components. It can also be thought of as publish/subscribe or pubsub.
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With