What is the best place to register and unregister to an event bus (like otto, EventBus, or tinybus) in an Activity and why?
Otto's example uses onResume()-onPause(), EventBus's mentions onStart()-onStop(), and we needed to use onCreate()-onDestroy() in our app to update the activity's UI even when it was in the background. So I guess it can be any of the three depending on the nature of the events and their handling, but I was wondering if there is anything more to it that should be considered.
@levavare, I think the correct time to register/unregister depends on your events and what you intend to do with them. And can be different for different events within the same application.
For example, I'm using EventBus in an Android app that monitors a realtime data logging device (Arduino, in this case) via Bluetooth. I have two quite different types of events.
The first event is posted by my Bluetooth code to notify one of my fragments that a new set of instrument readings has been received from the device. That fragment then writes them to a database table. It's important that event always be heard and acted on. The fragment registers/unregisters in its OnCreate/OnDestroy methods. I also subscribe for that event with elevated priority.
The other event is posted by the database layer when the new record is added to the database. I have a series of fragments that show different subsets of the readings (temperatures, pressures, alarm conditions). When one of those fragments is being viewed it should update as soon as the new reading is in the database. But when the fragment is out of sight, there's no reason for it to act on a reading. I have those fragments register/unregister in OnStart/OnStop. I was going to do that work in OnResume/OnPause and, frankly, I think it would work as well there for my app. But @Jordy's answer and link convinced me to go with OnStart/OnStop instead.