Using RxJava
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
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.