Event Aggregator Pattern featuring Otto

Event Aggregator Pattern featuring Otto

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

F94273df1de7575518ec18b97af43b90?s=128

Kevin McMahon

May 14, 2014
Tweet

Transcript

  1. 2.
  2. 3.
  3. 4.
  4. 6.

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

    extension, but closed for modification. 1 Bertrand Meyer
  5. 8.

    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.
  6. 10.

    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
  7. 11.
  8. 13.

    Introducing the Bus public final class BusProvider { private static

    final Bus BUS = new Bus(); public static Bus getInstance() { return BUS; } private BusProvider() { // No instances. } }
  9. 14.

    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); }
  10. 15.

    Publish Events Method public void post(Object event) { /*...*/ }

    Example BusProducer.getInstance().post(new LocationClearEvent());
  11. 16.

    Create Events Event objects are just POJOs that represent the

    types of events that occur in the app. public class LocationClearEvent { /*...*/ } public class LocationChangedEvent { /*...*/ }
  12. 18.

    @Subscribe public void onLocationChanged(LocationChangedEvent event) { // Action goes here

    } @Subscribe public void onLocationCleared(LocationClearEvent event) { // Action goes here }
  13. 19.

    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); } }); } } }