EventBus for Android
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share

EventBus for Android

  • 25,027 views
Uploaded 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.

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
No Downloads

Views

Total Views
25,027
On Slideshare
24,621
From Embeds
406
Number of Embeds
11

Actions

Shares
Downloads
334
Comments
2
Likes
61

Embeds 406

http://collab.lge.com 269
https://twitter.com 45
https://ssl14.ovh.net 32
http://www.verious.com 24
http://tieubao.22journeys.com 16
http://127.0.0.1 10
https://duckduckgo.com 5
http://www.linkedin.com 2
http://www.plurk.com 1
https://www.linkedin.com 1
http://tieubao.me 1

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 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 https://github.com/greenrobot/EventBus
  • 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 dialogbus.post(new 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 http://creativecommons.org/licenses/by-sa/3.0/ Contact greenrobot – http://greenrobot.de – http://twitter.com/greenrobot_de – Google+: http://bit.ly/greenrobotplus