Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Event Aggregator Pattern featuring Otto

Event Aggregator Pattern featuring Otto

May 2014 Android Listener presentation on the event aggregation pattern featuring Otto.

Kevin McMahon

May 14, 2014
Tweet

More Decks by Kevin McMahon

Other Decks in Programming

Transcript

  1. Software entities (classes, modules, functions, etc.) should be open for

    extension, but closed for modification. 1 Bertrand Meyer
  2. Listener Drawbacks 4 1:1 relationship between class and response 4

    Conflicting interface methods 4 Naming conventions (e.g. handleChangeEvent vs. recordChangeInJournal). 4 Each event usually has its own interface.
  3. 4 Brokers events between components via pub/sub communication 4 Components

    (activities, fragments, services) are blissfully ignorant of each other 4 Programming to a contract
  4. Introducing the Bus public final class BusProvider { private static

    final Bus BUS = new Bus(); public static Bus getInstance() { return BUS; } private BusProvider() { // No instances. } }
  5. Registration @Override protected void onResume() { super.onResume(); // Register ourselves

    so that we can provide the initial value. BusProvider.getInstance().register(this); } @Override protected void onPause() { super.onPause(); // Always unregister when an object no longer should be on the bus. BusProvider.getInstance().unregister(this); }
  6. Publish Events Method public void post(Object event) { /*...*/ }

    Example BusProducer.getInstance().post(new LocationClearEvent());
  7. Create Events Event objects are just POJOs that represent the

    types of events that occur in the app. public class LocationClearEvent { /*...*/ } public class LocationChangedEvent { /*...*/ }
  8. @Subscribe public void onLocationChanged(LocationChangedEvent event) { // Action goes here

    } @Subscribe public void onLocationCleared(LocationClearEvent event) { // Action goes here }
  9. public class AndroidBus extends Bus { private final Handler mainThread

    = new Handler(Looper.getMainLooper()); @Override public void post(final Object event) { if (Looper.myLooper() == Looper.getMainLooper()) { super.post(event); } else { mainThread.post(new Runnable() { @Override public void run() { AndroidBus.super.post(event); } }); } } }