Intro to Android

Lab: Event Bus

Event buses are a great way to decouple our components without using a interface or listener pattern that can produce a lot of boilerplate code.

Otto is a system-wide notification system. A component (e.g. an Activity or Fragment) posts an event, with an optional message, to Otto. Other components that have registered for events will receive the event and react as appropriate.

Let's add an Otto Bus!

Integrate Otto

If not already present, add the maven dependency to your pom.xml file so that we can reference Otto throughout our project.

    <!--Event Bus-->
    <dependency>
        <groupId>com.squareup</groupId>
        <artifactId>otto</artifactId>
        <version>1.3.4</version>
    </dependency>

Application bus

Now add these lines to our CalculatorApplication.java class.

private Bus bus;

public Bus getBus()
{
    return bus;
}

public static void postToBus( BaseEvent event)
{
    // Note: Auto Generating BaseEvent next
    getInstance().getBus().post( event );
}

@Override
public void onCreate()
{
    super.onCreate();
    instance.bus = new Bus();
}

The function postToBus() gives us a convenient way post to the bus from any activity or fragment in our application. If we build all of our events to extend the BaseEvent then we can use this for all events in the application.

Create BaseEvent

Create a file called BaseEvent.java. I suggest creating a package called events to hold events and create further packages as needed to keep your code organized.

The event can be quite simple, or you can include data with your events. In this case, we will make it as basic as possible:

public class BaseEvent { }

Add a test & commit

Let's make sure that the Bus exists for our application. First we'll need to migrate our application to a field and initialize in setUp(). Then we can add this test:

@Test
public void shouldHaveBus() throws Exception
{
    assertNotNull( application.getBus() );
}

Once all the tests pass, commit to your repository.