This presentation explains what an Event Bus is, where it is used in Android apps, what are the native alternatives, what libraries are available in open source community, and pros and cons of native/third party solutions.
2. Introduction
● What is an Event Bus?
● Callback vs Broadcast Receiver vs Event Bus
● Event Bus Libraries for Android
▪ Otto by Square (deprecated on January 15, 2016)
▪ EventBus by greenrobot
▪ RxJava by ReactiveX
● Q/A
● References
3. What is an Event Bus?
● System Bus
● Central hub
● Flexible and modular
4. What is an Event Bus?
How can I pass value from X to Y when click on Z?
● Callback (a.k.a Listener)
● Broadcast Receiver
● Event Bus
5. What is an Event Bus?
Common Crash in Android
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1341)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1352)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
6. What is an Event Bus?
Callback
/**
* Interface definition for a callback to be invoked when a view is clicked.
*/
public interface OnClickListener {
/**
* Called when a view has been clicked.
*
* @param v The view that was clicked.
*/
void onClick(View v);
}
7. What is an Event Bus?
Broadcast Receiver
private MyReceiver mReceiver;
void onResume() {
IntentFilter filter = new IntentFilter("com.example.MyEvent");
mReceiver = new MyReceiver();
registerReceiver(receiver, filter);
}
void onPause() {
unregisterReceiver(mReceiver);
}
public class MyReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "MyEvent", Toast.LENGTH_LONG).show();
}
}
}
8. What is an Event Bus?
Broadcast Receiver
public void sendBroadcast() {
Intent intent = new Intent("com.example.MyEvent");
intent.putExtra("myParam", "Hello");
sendBroadcast(intent);
}
9. What is an Event Bus?
Event Bus
● Publish & Subscribe Pattern implementation (similar to Observable)
● Component to component communication without direct reference
● Three well-known libraries for Android
▪ Otto by Square (deprecated on January 15, 2016)
▪ EventBus by greenrobot
▪ RxJava by ReactiveX
11. Callback vs Broadcast Receiver vs Event Bus
Callback
Pros
● Easy to implement for small projects
Cons
● Excessive amount of boilerplate code
● Unnecessary method overrides
12. Callback vs Broadcast Receiver vs Event Bus
Broadcast Receiver
Pros
● Native solution to problem
▪ Consistency in the code
Cons
● Too much code for a simple task
13. Callback vs Broadcast Receiver vs Event Bus
Event Bus
Pros
● Cleaner, maintainable, extensible, flexible and more readable code
● Easier to test
● Multiple receivers
● Subscribing to events you need
● No direct reference between components
Cons
● Hard to maintain list of publishers (fewer publisher recommended)
● No auto-complete support from IDE
● Powerful but easily can be abused
14. Otto by Square
Event Bus Libraries for Android
● Fork of Guava based Event Bus
● Designed for Android
● Deprecated on January 15, 2016
15. Otto by Square
Event Bus Libraries for Android
public class UpdateDataEvent {
public String data;
public UpdateDataEvent(String data) {
this.data = data;
}
}
16. Otto by Square
Event Bus Libraries for Android
// Use as a singleton
Bus bus = new Bus();
// Publish an event. Posting to the bus is a synchronous action.
bus.post(new UpdateDataEvent("New Data!"));
// Subscribe to a specific event. Any method name. As long as annotated with @Subscribe
@Subscribe
public void dataUpdated(UpdateDataEvent event) {
// React to the event (ex. update UI, save data to database)
Log.v(TAG, "Data: " + event.data);
}
17. Otto by Square
Event Bus Libraries for Android
// Register your class
bus.register(this); // inside onStart() method
bus.unregister(this); // inside onStop() method
// Produce
@Produce
public UpdateDataEvent produceDataUpdate() {
// Assuming data exists.
return new AnswerAvailableEvent(this.data);
}
18. EventBus by greenrobot
Event Bus Libraries for Android
● Developers of greenDAO
● Same basic semantics as Otto
● Faster than Otto
● Richer feature set
19. EventBus by greenrobot
Event Bus Libraries for Android
public class UpdateDataEvent {
public String data;
public UpdateDataEvent(String data) {
this.data = data;
}
}
20. EventBus by greenrobot
Event Bus Libraries for Android
// Similar to Otto
EventBus bus = EventBus.getDefault();
// With richer feature set
EventBus bus = EventBus.builder().logNoSubscriberMessages(false).sendNoSubscriberEvent(false).build();
EventBus bus = EventBus.builder().throwSubscriberException(true).build();
// Must be called once. FOr example, in Application class’ onCreate() method
EventBus.builder().throwSubscriberException(BuildConfig.DEBUG).installDefaultEventBus();
// Publish an event
bus.post(new UpdateDataEvent("New data!"));
21. EventBus by greenrobot
Event Bus Libraries for Android
// Register your class
bus.register(this); // inside onStart() method
bus.unregister(this); // inside onStop() method
// Subscribe to a specific event. Any method name. As long as annotated with @Subscribe
@Subscribe
public void dataUpdated(UpdateDataEvent event) {
// React to the event (ex. update UI, save data to database)
Log.v(TAG, "Data: " + event.data);
}
22. EventBus by greenrobot
Event Bus Libraries for Android
@Subscribe(threadMode = ThreadMode.POSTING) // Opt.
public void onMessage(MessageEvent event) {
log(event.message);
}
ThreadMode
● POSTING
▪ Default ThreadMode
▪ Good for simple tasks
● MAIN
▪ Runs on main/UI thread
● BACKGROUND
● ASYNC @Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessage(MessageEvent event){
saveToDisk(event.message);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessage(MessageEvent event) {
textField.setText(event.message);
}
23. EventBus by greenrobot
Event Bus Libraries for Android
// Posting a Sticky Event
bus.postSticky(new LastLocationEvent("Omaha!"));
Sticky Events
● Last sticky event kept in memory
● Delivered to subscriber as soon as
registered
@Override
public void onStart() {
super.onStart();
bus.register(this);
}
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onEvent(LastLocationEvent event) {
textField.setText(event.message);
}
@Override
public void onStop() {
bus.unregister(this);
super.onStop();
}
24. RxJava by ReactiveX
Event Bus Libraries for Android
// this is the middleman object
public class RxBus {
private Subject<Object, Object> bus = new
SerializedSubject<>(PublishSubject.create());
public void send(Object o) {
bus.onNext(o);
}
public Observable<Object> toObserverable() {
return bus;
}
}
@OnClick(R.id.btn_demo_rxbus_tap)
public void onTapButtonClicked() {
bus.send(new TapEvent());
}
bus.toObserverable()
.subscribe(new Action1<Object>() {
@Override
public void call(Object event) {
if(event instanceof TapEvent) {
_showTapText();
}else if(event instanceof SomeOtherEvent) {
_doSomethingElse();
}
}
});