Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 738
dev Avatar asked Aug 03 '15 23:08

dev


People also ask

What is EventBus used for?

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.

Is EventBus an anti pattern?

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.

Should we use EventBus?

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.

What is JavaScript EventBus?

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.


1 Answers

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

like image 75
shredder Avatar answered Oct 20 '22 21:10

shredder