Thursday, October 24, 2013

on Leave a Comment

Android Quick Tip: Handling Child Object Event Registration with Otto.

As I have mentioned before, I am a big fan of the pub/sub or service bus pattern in Android. I feel that tools like Otto simplify the code base when compared to Broadcast Receivers and Intents.

Recently I ran into an issue where I wanted sub views of my activities and fragments to register with the event bus in Otto. When you handle bus registration in your activities and fragments, unregistering for events is trivial because you can tie directly in to the life cycle methods. Unfortunately sub views will not tie in directly with those methods.



After a little bit of searching I found that I am not the first person to come across this problem. The generally agreed upon solution seems to be the creating of a scoped bus. Jake Wharton provided a gist the covers the basic idea. I felt like this gist needed more publicity as the issue may not be obvious to some who are trying to use a service bus to drive their application.

The scoped bus works by storing an object list of the activity or fragment's child objects that are registered with the bus. Where we would normally update the registration of the Activity we are now adding or removing all of the registered objects. Note that in Jake's example above the activity is not being unregistered. You will need to add this yourself if you need the activity to receive events from the service bus.
Powered by Blogger.