Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
EventBusfor Android.droidcon NL23.11.2012Markus Junginger      © Copyright 2012 Markus Junginger.                       Al...
Random Qoutes
Status Quo in Android Q: Who is talking to whom?
Status Quo in Android                                   Activity             Activity                                     ...
Communication Issues?! Tight coupling of components   Inflexible, changes are expensive Boiler plate code  – Define int...
EventBus Communication   Activity                  Activity               Event                Bus                        ...
EventBus for Android   Event-based Publish/Subscribe   Bus: central communication   Inspired by Guava„s EventBus (Googl...
EventBus in 4 Steps1. Define an event2. Register subscriber3. Post an event4. Receive the event
EventBus in 4 Steps: Code!1. Define an event  public class MyEvent {}2. Register subscriber  EventBus.getDefault().registe...
Publish / Subscribe                                        Subscriber                              Event             Event...
EventBus Instances EventBus instances Instances are indepent from each other For many apps, a single instance is fine ...
Event Handler Method:onEvent EventBus scans subscribers  – During (first) registration of subscriber  – For event handler...
Type-based Event Routing Event type: Java class of the event To receive an event, its type must match post(new MyEvent(...
Event Type is a Filter                                           Subscriber                                 Event         ...
It„s time to see someCODE
EventBus Code: SenderMyEvent myEvent = new MyEvent(anyData);EventBus.getDefault().post(myEvent);
EventBus Code: ReceiverMyActivity extends Activity // no interf.// onCreate or onResumeEventBus.getDefault().register(this...
Example: Fragment toFragment   Tap on one fragment   Another fragment reacts   Typical list/details scenario   Convent...
Conventional: DetailFragment// Here‘s the action. How is it called?public void loadDetails(Item item) {  …}
Conventional: ListFragmentinterface Contract {     void onItemSelected(Item item);}// Propagate to Activity((Contract)getA...
Conventional: Activitypublic class MyActivity implementsListFragment.Contract {    public void onItemSelected(Item item) {...
EventBus: Event classpublic class ItemSelectedEvent {  public final Item item;    public ItemSelectedEvent(Item item) {   ...
EventBus: Post & Receive// In ListFragmentEventBus.getDefault().post(new     ItemSelectedEvent(item));// In DetailFragment...
Event Delivery in other ThreadsTHREADING SUPPORT
Why do Threads matter? Responsive UI, Android conventions  – Main/UI thread must not block  – UI updates in the main thre...
EventBus Threading Support Event delivery using threads Event handler method decides  (handler knows best what it is doi...
Thread Modes PostThread: Direct call in same thread MainThread: UI updates etc. BackgroundThread: „not the main  thread...
Threading Example Network thread posts result post(new UserLoginEvent(name)); Fragment reacts to event in main thread pu...
Asynchronous execution and error dialogsSNEAK PREVIEW
Upcoming: EventBus 2.1 EventBus 2.1 is not final yet;  Still gathering experience and feedback Everything pushed to mast...
EventBus 2.1: AsyncExecutor A thread pool, but with failure handling RunnableEx interface  – Like Runnable to define cod...
AsyncExecutor: Calling CodeAsyncExecutor.create().execute(  new RunnableEx {    public void run throws LoginException {   ...
AsyncExecutor: ReceivingCodepublic voidonEventMainThread(LoggedInEvent event) {  // Change some UI}
Comparison to AsyncTask AsyncExecutor advantages  – Don‟t worry about configuration changes    (typically device rotation...
EventBus 2.1: Error Dialog Operations may fail (networking, etc.) Some UI response should be shown  – Currently: error d...
How Error Dialogs work Error handling “attaches” to Activities Displaying dialogs is triggered by events ThrowableFailu...
Error Dialogs: Code// In onCreate in your ActivityErrorDialogManager.attachTo(this);// Trigger the dialogbus.post(new Thro...
Dialog Configuration Which texts to display in the dialog? Simple option: Configure  – Supply default resources for titl...
Dialog Configuration: Code// Initialize in your Application classErrorDialogConfig config = new  ErrorDialogConfig(getReso...
Comparison AndroidBroadcast Nice, but somewhat inconvenient BroadcastReceiver has to be extended Registration needed fo...
Tiny bits and some other stuffTIPPS AND SNIPPS
Sticky Events Events can be posted using sticky mode postSticky(event); // Instead of post(…) The last sticky event is k...
Events Class Event classes are tiny; group thempublic class Events {  public static class InitThreadCompleteEvent {  }   ...
EventBusFragment/-Activity Superclass depends on your setup Implement in your project class EventBusFragment extends Fra...
When to use EventBus Medium/high distance of components:  “Somewhere” else should happen sth. Potentially multiple depen...
License, Contact This presentation is licensed under  CreativeCommons ShareAlike/Attribution http://creativecommons.org/l...
EventBus for Android
Upcoming SlideShare
Loading in …5
×

EventBus for Android

69,823 views

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.

Published in: Technology

EventBus for Android

  1. 1. EventBusfor Android.droidcon NL23.11.2012Markus Junginger © Copyright 2012 Markus Junginger. All rights reserved.
  2. 2. Random Qoutes
  3. 3. Status Quo in Android Q: Who is talking to whom?
  4. 4. Status Quo in Android Activity Activity Service / Helper Fragment Fragment Thread
  5. 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. 6. EventBus Communication Activity Activity Event Bus Service / Helper Fragment Fragment Thread
  7. 7. EventBus for Android Event-based Publish/Subscribe Bus: central communication Inspired by Guava„s EventBus (Google) Android-optimized Open Source, Apache 2 License https://github.com/greenrobot/EventBus
  8. 8. EventBus in 4 Steps1. Define an event2. Register subscriber3. Post an event4. Receive the event
  9. 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. 10. Publish / Subscribe Subscriber Event Event Event onEvent() Publisher post() Bus Event Subscriber onEvent()
  11. 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. 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. 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. 14. Event Type is a Filter Subscriber Event Event Event onEvent(MyEvent) Publisher post Bus (MyEvent) Subscriber onEvent(OtherEvent)
  15. 15. It„s time to see someCODE
  16. 16. EventBus Code: SenderMyEvent myEvent = new MyEvent(anyData);EventBus.getDefault().post(myEvent);
  17. 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. 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. 19. Conventional: DetailFragment// Here‘s the action. How is it called?public void loadDetails(Item item) { …}
  20. 20. Conventional: ListFragmentinterface Contract { void onItemSelected(Item item);}// Propagate to Activity((Contract)getActivity()).onItemSelected(item);
  21. 21. Conventional: Activitypublic class MyActivity implementsListFragment.Contract { public void onItemSelected(Item item) { DetailFragment detailFragment = (DetailFragment) getFragmentManager().findFragmentBy…; detailFragment.loadDetails(item); }}
  22. 22. EventBus: Event classpublic class ItemSelectedEvent { public final Item item; public ItemSelectedEvent(Item item) { this.item = item; }}
  23. 23. EventBus: Post & Receive// In ListFragmentEventBus.getDefault().post(new ItemSelectedEvent(item));// In DetailFragment (extends EventBusFragment)public void onEvent(ItemSelectedEvent event) {…}
  24. 24. Event Delivery in other ThreadsTHREADING SUPPORT
  25. 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. 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. 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. 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. 29. Asynchronous execution and error dialogsSNEAK PREVIEW
  30. 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. 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. 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. 33. AsyncExecutor: ReceivingCodepublic voidonEventMainThread(LoggedInEvent event) { // Change some UI}
  34. 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. 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. 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. 37. Error Dialogs: Code// In onCreate in your ActivityErrorDialogManager.attachTo(this);// Trigger the dialogbus.post(new ThrowableFailureEvent(ex));// Or let AsyncExecutor do it for you…
  38. 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. 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. 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. 41. Tiny bits and some other stuffTIPPS AND SNIPPS
  42. 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. 43. Events Class Event classes are tiny; group thempublic class Events { public static class InitThreadCompleteEvent { } public static class LoginCompleteEvent { }}
  44. 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. 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. 46. License, Contact This presentation is licensed under CreativeCommons ShareAlike/Attribution http://creativecommons.org/licenses/by-sa/3.0/ Contact greenrobot – http://greenrobot.de – http://twitter.com/greenrobot_de – Google+: http://bit.ly/greenrobotplus

×