0

How many events should i post for a single Event Bus? For Example -

Registering Event Bus - EventBus.getDefault().register(this);

Posting Event - EventBus.getDefault().post(Object);

And is there any problem causes if i could not unregister the EventBus

sanil
  • 482
  • 1
  • 7
  • 23

2 Answers2

1

You can post as much as you want events. If you dont call unregister, events will be delievered for example on your closed activity.You will have a memory leak, beacuse EventBus will contain a reference of your closed activity. Also this can produce an exaption, for example you will do some interecation with your view, that is become null when you closed activity, in EventBus subscribe method.

Igori S
  • 123
  • 8
1

There's no limitations to number of events in EventBus.

If the lifetime of the object you've registered to the EventBus is shorter than the lifetime of the EventBus (which is typically the same as application lifetime), you definitely need to unregister from EventBus. If you don't, the registered object will always have a reference to it inside the EventBus which will prevent the garbage collector from doing its job.

Say you have a file viewer activity which subscribes to an event. You can open a file, look at it, close the activity and open another file which uses the same activity. Now if you don't unsubscribe from EventBus all of the activities, that the user opens, will have a reference to them inside EventBus. They will never be garbage collected and so eventually the application would run out of memory.

Zharf
  • 2,638
  • 25
  • 26
  • Is there any problem if i register EventBus multiple times like registering EventBus in 2 different activities? – sanil Mar 09 '17 at 13:15
  • @sanil you mean registering multiple instance at the same time? no. Registering the same instance multiple times throws an exception though. – Zharf Mar 09 '17 at 13:21
  • i mean - In FirstActivity.java - EventBus.getDefault().register(this); – sanil Mar 09 '17 at 13:39
  • SecondActivity.java - EventBus.getDefault().register(this); so both will be the different instances right?? – sanil Mar 09 '17 at 13:40
  • yep that's fine, just remember to unregister them as well – Zharf Mar 09 '17 at 14:39
  • that means if i register 10 event buses for 10 different activities and then unregister them repectively will not cause any problem to the app? – sanil Mar 10 '17 at 06:16
  • That's fine, you would generally want to register for events in onStart and unregister in onStop though – Zharf Mar 10 '17 at 09:00