Random thoughts, musings, and tech stuff

24 Apr 2013, 04:12

Share

Playing around with Otto on Android

There are a few nice Open Source libraries for Android that Square has published. One of them is Otto, which is a Guava-based event bus system that uses annotations and code generation. Basically, it saves you from needing to create a bunch of interfaces and register them between various parts of your code. Instead, all you need to do is register with the singleton bus, and subscribe to events.

Here’s the sample bus provider that Square published with its sample app:

Next up, register with the bus. This can be done in your Activity’s onCreate, or better register it in onResume, and unregister onPause:

Events can be published on the bus using the ‘post’ method. The object type and the subscribers determine automatically where your event gets routed. Here’s an example showing an event being fired when a button is clicked:

Subscribing to events is very simple. Again, the object being passed is what determines the event routing.