Your SlideShare is downloading. ×
EventBus for Android
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.

Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

EventBus for Android


Published on

EventBus is an Android optimized publish/subscribe event bus. A typical use case for Android apps is gluing Activities, Fragments, and background threads together.

EventBus is an Android optimized publish/subscribe event bus. A typical use case for Android apps is gluing Activities, Fragments, and background threads together.

Published in: Technology
No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 1. EventBusfor Android.droidcon NL23.11.2012Markus Junginger © Copyright 2012 Markus Junginger. All rights reserved.
  • 2. Random Qoutes
  • 3. Status Quo in Android Q: Who is talking to whom?
  • 4. Status Quo in Android Activity Activity Service / Helper Fragment Fragment Thread
  • 5. Communication Issues?! Tight coupling of components  Inflexible, changes are expensive Boiler plate code – Define interfaces – Callbacks for asynch. communication – Listener management – Propagation through all layers
  • 6. EventBus Communication Activity Activity Event Bus Service / Helper Fragment Fragment Thread
  • 7. EventBus for Android Event-based Publish/Subscribe Bus: central communication Inspired by Guava„s EventBus (Google) Android-optimized Open Source, Apache 2 License
  • 8. EventBus in 4 Steps1. Define an event2. Register subscriber3. Post an event4. Receive the event
  • 9. EventBus in 4 Steps: Code!1. Define an event public class MyEvent {}2. Register subscriber EventBus.getDefault().register(this);3. Post an event EventBus.getDefault().post(event);4. Receive the event public void onEvent(MyEvent event);
  • 10. Publish / Subscribe Subscriber Event Event Event onEvent() Publisher post() Bus Event Subscriber onEvent()
  • 11. EventBus Instances EventBus instances Instances are indepent from each other For many apps, a single instance is fine „Convenience“ Instance EventBus.getDefault() Aquire it anywhere(!) in your code
  • 12. Event Handler Method:onEvent EventBus scans subscribers – During (first) registration of subscriber – For event handler methods Event handler methods – Naming convention: onEvent – public visibility – No return value (void) – Single parameter for the event to receive
  • 13. Type-based Event Routing Event type: Java class of the event To receive an event, its type must match post(new MyEvent());  onEvent(MyEvent event) {…} Type hierarchy of events – Implement logging of all events: onEvent(Object event)
  • 14. Event Type is a Filter Subscriber Event Event Event onEvent(MyEvent) Publisher post Bus (MyEvent) Subscriber onEvent(OtherEvent)
  • 15. It„s time to see someCODE
  • 16. EventBus Code: SenderMyEvent myEvent = new MyEvent(anyData);EventBus.getDefault().post(myEvent);
  • 17. EventBus Code: ReceiverMyActivity extends Activity // no interf.// onCreate or onResumeEventBus.getDefault().register(this);// onDestroy or onPauseEventBus.getDefault().unregister(this);public onEvent(MyEvent event) { … }
  • 18. Example: Fragment toFragment Tap on one fragment Another fragment reacts Typical list/details scenario Conventional setup: Activity Activity is managing Fragments Fragment Fragment
  • 19. Conventional: DetailFragment// Here‘s the action. How is it called?public void loadDetails(Item item) { …}
  • 20. Conventional: ListFragmentinterface Contract { void onItemSelected(Item item);}// Propagate to Activity((Contract)getActivity()).onItemSelected(item);
  • 21. Conventional: Activitypublic class MyActivity implementsListFragment.Contract { public void onItemSelected(Item item) { DetailFragment detailFragment = (DetailFragment) getFragmentManager().findFragmentBy…; detailFragment.loadDetails(item); }}
  • 22. EventBus: Event classpublic class ItemSelectedEvent { public final Item item; public ItemSelectedEvent(Item item) { this.item = item; }}
  • 23. EventBus: Post & Receive// In ListFragmentEventBus.getDefault().post(new ItemSelectedEvent(item));// In DetailFragment (extends EventBusFragment)public void onEvent(ItemSelectedEvent event) {…}
  • 24. Event Delivery in other ThreadsTHREADING SUPPORT
  • 25. Why do Threads matter? Responsive UI, Android conventions – Main/UI thread must not block – UI updates in the main thread – Networking etc. in background threads Threads and Events – Thread posting events – Thread handling events – Posting and handling thread may differ
  • 26. EventBus Threading Support Event delivery using threads Event handler method decides (handler knows best what it is doing) Naming conventions for onEvent methods To deliver in the main thread: onEventMainThread(…) (All methods beginning with onEvent are checked for typos)
  • 27. Thread Modes PostThread: Direct call in same thread MainThread: UI updates etc. BackgroundThread: „not the main thread“ Async: always asynchronous to posting Used in the method name: onEventXXX No additional code required
  • 28. Threading Example Network thread posts result post(new UserLoginEvent(name)); Fragment reacts to event in main thread public void onEventMainThread(UserLoginEvent e) { textView.setText(e.getName()); }
  • 29. Asynchronous execution and error dialogsSNEAK PREVIEW
  • 30. Upcoming: EventBus 2.1 EventBus 2.1 is not final yet; Still gathering experience and feedback Everything pushed to master branch No relevant changes in the core (planned) Comes with some helpers – AsyncExecutor – Error dialog
  • 31. EventBus 2.1: AsyncExecutor A thread pool, but with failure handling RunnableEx interface – Like Runnable to define code to run async. – May throw any execption ThrowableFailureEvent – Posted when exception occurs – Throwable object is wrapped inside – Subclass to customize and filter for type
  • 32. AsyncExecutor: Calling CodeAsyncExecutor.create().execute( new RunnableEx { public void run throws LoginException { remote.login(); EventBus.getDefault().postSticky( new LoggedInEvent()); // No need to catch Exception } }}
  • 33. AsyncExecutor: ReceivingCodepublic voidonEventMainThread(LoggedInEvent event) { // Change some UI}
  • 34. Comparison to AsyncTask AsyncExecutor advantages – Don‟t worry about configuration changes (typically device rotation) – Failure handling – EventBus (other dependencies somewhere?) AsyncTask advantage – Canceling task
  • 35. EventBus 2.1: Error Dialog Operations may fail (networking, etc.) Some UI response should be shown – Currently: error dialogs – Later: Possibly maybe someth. Crouton-ish Multiple errors: don‟t open multiple times Goal: Minimize required code
  • 36. How Error Dialogs work Error handling “attaches” to Activities Displaying dialogs is triggered by events ThrowableFailureEvent or subclass – AsyncExecutor sends those – Or post those events manually
  • 37. Error Dialogs: Code// In onCreate in your ActivityErrorDialogManager.attachTo(this);// Trigger the ThrowableFailureEvent(ex));// Or let AsyncExecutor do it for you…
  • 38. Dialog Configuration Which texts to display in the dialog? Simple option: Configure – Supply default resources for title and text – Map exception types  texts Flexible option: extend ErrorDialogFragmentFactory
  • 39. Dialog Configuration: Code// Initialize in your Application classErrorDialogConfig config = new ErrorDialogConfig(getResources(), R.string.error_generalTitle, R.string.error_general);config.addMapping(UnknownHostException.class, R.string.error_noInternetConnection);config.addMapping(IOException.class, R.string.error_generalServer);ErrorDialogManager.factory = new ErrorDialogFragmentFactory.Support(config);
  • 40. Comparison AndroidBroadcast Nice, but somewhat inconvenient BroadcastReceiver has to be extended Registration needed for every event type Extra work to filter for desired event types (IntentFilter with e.g. ACTION String) Data is converted into Intent extras
  • 41. Tiny bits and some other stuffTIPPS AND SNIPPS
  • 42. Sticky Events Events can be posted using sticky mode postSticky(event); // Instead of post(…) The last sticky event is kept in memory Registration with getting sticky events registerSticky(subscriber); Query for sticky event getStickyEvent(Class<?> eventType) Remove sticky event (Class or Object) removeStickyEvent(Class<?> eventType)
  • 43. Events Class Event classes are tiny; group thempublic class Events { public static class InitThreadCompleteEvent { } public static class LoginCompleteEvent { }}
  • 44. EventBusFragment/-Activity Superclass depends on your setup Implement in your project class EventBusFragment extends Fragment { public void onCreate(…) { super.onCreate(…); EventBus.getDefault().register(this); } public void onDestroy() { EventBus.getDefault().unregister(this); super.onDestroy(); }
  • 45. When to use EventBus Medium/high distance of components: “Somewhere” else should happen sth. Potentially multiple dependencies Asynchronous logic When not to use EventBus – Strictly internal matters: Use methods and interfaces instead – Inter-process communication
  • 46. License, Contact This presentation is licensed under CreativeCommons ShareAlike/Attribution Contact greenrobot – – – Google+: