For the More Curious: Local Events

Broadcast intents allow you to propagate information across the system in a global fashion. What if you want to broadcast the occurrence of an event within your app’s process only? Using an event bus is a great alternative.

An event bus operates on the idea of having a shared bus, or stream of data, that components within your application can subscribe to. When an event is posted to the bus, subscribed components will be activated and have their callback code executed.

EventBus by greenrobot is a third-party event bus library we use in our Android applications. Other alternatives to consider include Square’s Otto, which is another event bus implementation, or using RxJava Subjects and Observables to simulate an event bus.

Android does provide a local way to send broadcast intents, called LocalBroadcastManager. But we find that the third-party libraries mentioned here provide a more flexible and easier-to-use API for broadcasting local events.

Using EventBus

To use EventBus in your application, you must add a library dependency to your project. Once the dependency is set up, you define a class representing an event (you can add fields to the event if you need to pass data along):

public class NewFriendAddedEvent { }

You can post to the bus from just about anywhere in your app:

EventBus eventBus = EventBus.getDefault();
eventBus.post(new NewFriendAddedEvent());

Other parts of your app can subscribe to receive events by first registering to listen on the bus. Often you will register and unregister activities or fragments in corresponding lifecycle methods, such as onStart(…) and onStop(…):

// In some fragment or activity...
private EventBus mEventBus;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mEventBus = EventBus.getDefault();
}

@Override
public void onStart() {
    super.onStart();
    mEventBus.register(this);
}

@Override
public void onStop() {
    super.onStop();
    mEventBus.unregister(this);
}

You specify how a subscriber should handle an event by implementing a method with the appropriate event type as input and adding the @Subscribe annotation to that method. Using the @Subscribe annotation with no parameters means the event will be processed on the same thread it was sent from. You could instead use @Subscribe(threadMode = ThreadMode.MAIN) to ensure that the event is processed on the main thread if it happens to be issued from a background thread.

// In some registered component, like a fragment or activity...
@Subscribe(threadMode = ThreadMode.MAIN)
public void onNewFriendAdded(NewFriendAddedEvent event){
    Friend newFriend = event.getFriend();
    // Update the UI or do something in response to event...
}

Using RxJava

RxJava can also be used to implement an event broadcasting mechanism. RxJava is a library for writing reactive-style Java code. That reactive idea is broad and beyond the scope of what we can cover here. The short story is that it allows you to publish and subscribe to sequences of events and gives you a broad set of generic tools for manipulating these event sequences.

So you could create something called a Subject, which is an object you can publish events to as well as subscribe to events on.

Subject<Object, Object> eventBus =
    new SerializedSubject<>(PublishSubject.create());

You can publish events to it:

Friend someNewFriend = ...;
NewFriendAddedEvent event = new NewFriendAddedEvent(someNewFriend);
eventBus.onNext(event);

and subscribe to events on it:

eventBus.subscribe(new Action1<Object>() {
    @Override
    public void call(Object event) {
        if (event instanceof NewFriendAddedEvent) {
            Friend newFriend = ((NewFriendAddedEvent)event).getFriend();
            // Update the UI
        }
    }
})

The advantage of RxJava’s solution is that your eventBus is now also an Observable, RxJava’s representation of a stream of events. That means that you get to use all of RxJava’s various event manipulation tools. If that piques your interest, check out the wiki on RxJava’s project page: github.com/​ReactiveX/​RxJava/​wiki.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.146.223