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

Reactions on the Bus

Reactions on the Bus

Survey of Message Buses and Reactive Programming in Mobile Apps

Maciej Matyjas

January 27, 2014
Tweet

More Decks by Maciej Matyjas

Other Decks in Programming

Transcript

  1. Reactions on the Bus: The Emergence of New Architectures for

    Mobile Apps Maciej Matyjas, Mobile Technology Lead
  2. 3 The Emergence of New Architectures for Mobile Apps • 

    Motivations •  Message Buses •  NSNotificationCenter •  LocalBroadcastManager •  Otto •  Reactive Programming •  Mobile Reactive Pioneers •  JavaRx on Android •  ReactiveCocoa •  Bacon.js •  Conclusions REACTIONS ON THE BUS
  3. 4 Motivations •  User context is king •  Benefits of

    async •  Real-time Features •  Multi-core THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS
  4. 5 User Context is King (esp. on Mobile) •  Connection

    type •  Battery level •  Location •  Upcoming reservations •  Time of day •  Sensors MOTIVATIONS
  5. 6 Motivations •  Mobile devices prefer asynchronous events •  Less

    battery usage •  Push Notifications •  Nobody likes polling •  Real-time features •  Likes, comments, shares •  Prices •  Analytics •  Lets use those cores THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS
  6. 8 Message Buses •  Early origins in 1960s telecoms systems

    •  Main benefit is de-coupling producers and consumers •  Event publishing can be non-blocking THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS
  7. 10 Message Buses •  Bus is responsible for •  Delivery

    •  Queuing •  Filtering •  Batching •  Persistence •  Performance controlled via •  Queue depth •  Number of consumers •  ‘Bandwidth’ of bus THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS
  8. 12 NSNotificationCenter •  Not exactly new •  Provided by Apple

    for system and app-internal notifications •  One notification center instance per app* •  Notifications are posted by calling thread •  Unless Notification Queue is used •  On receive notification, explicitly choose your thread •  Block style keeps it all in one place •  Coalescing THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS
  9. 13 NSNotificationCenter __block id observer = [[NSNotificationCenter defaultCenter]! addObserverForName: HDCImageNotifications.didDownloadImage

    " object: nil " queue: [NSOperationQueue mainQueue] " usingBlock: ^(NSNotification *note) {! ! if (--outstandingDownloads == 0){! "[[NSNotificationCenter defaultCenter] ! "removeObserver: observer];! "[self notify:kGHUnitWaitStatusSuccess forSelector:@selector(testupdatePriority_forDownloadWithURL)];! " " " "}! }]; THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS Hotels.com Unit Tests
  10. 15 LocalBroadcastManager •  Part of original Android APIs •  Cousin

    of BroadcastReceiver •  Blocking and async options •  Typically start a service on receive THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS
  11. 16 LocalBroadcastManager @Override public void onResume() { super.onResume(); // Register

    mMessageReceiver to receive messages. LocalBroadcastManager.getInstance(this). registerReceiver(mMessageReceiver, new IntentFilter("my-event")); } // handler for received Intents for the "my-event" event private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Extract data included in the Intent String message = intent.getStringExtra("message"); Log.d("receiver", "Got message: " + message); } }; THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html
  12. 18 Otto •  Made by Square •  Designed for use

    as a Singleton (doesn’t have to be) •  Create your Bus with a ThreadEnforcer •  Prefers annotations over interfaces THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS
  13. 19 Otto BusProvider.getInstance().post(produceLocationEvent()); @Produce public LocationChangedEvent produceLocationEvent() { // Provide

    an initial value for location based on the last known position. return new LocationChangedEvent(lastLatitude, lastLongitude); } @Subscribe public void onLocationChanged(LocationChangedEvent event) { locationEvents.add(0, event.toString()); if (adapter != null) { adapter.notifyDataSetChanged(); } } THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS https://github.com/square/otto
  14. 22 Reactive Programming •  Spreadsheets FTW •  Events over time

    as first class citizens •  Functional Reactive Programming •  MS and Rx THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS
  15. 23 Reactive Programming THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE

    APPS XE API £ Textfield Map key presses to val Map key presses to val Dampen Dampen Map Latest Bitcoin Textfield
  16. 25 QML •  From Qt •  Cross platform, mobile specific

    •  Declarative •  Looks like JSON •  Complete JavaScript environment •  Property Bindings MOBILE REACTIVE PIONEERS
  17. 26 QML Rectangle {! function calculateMyHeight() {! return Math.max(otherItem.height, !

    ! ! ! ! !thirdItem.height);! }! anchors.centerIn: parent! width: Math.min(otherItem.width, 10)! height: calculateMyHeight()! color: { if (width > 10) "blue"; ! ! ! else "red" }! } MOBILE REACTIVE PIONEERS http://en.wikipedia.org/wiki/QML#Property_bindings
  18. 28 KVO •  Apple magic •  Key Value Observing • 

    MVC with view Observing the Model MOBILE REACTIVE PIONEERS
  19. 29 KVO [self addObserver: self ! "forKeyPath: @"imageView.image" ! "options:

    NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew ! "context: nil];! -  (void) observeValueForKeyPath:(NSString *)keyPath ! "ofObject:(id)object ! "change:(NSDictionary *)change ! "context:(void *)context {! ! if (self.imageView.image) {! [self.activityIndicator stopAnimating];! ! // Constant values may be up to 2000, but autolayout constrains to a maximum! self.imageWidth.constant = self.imageView.image.size.width;! self.imageHeight.constant = self.imageView.image.size.height;! } else {! [self.activityIndicator startAnimating];! }! } MOBILE REACTIVE PIONEERS Hotels.com Gallery Image Cell
  20. 31 JavaRx on Android •  Java port of Rx by

    NetFlix •  Observables (like Iterables, but pushed) •  Parameterized concurrency •  Kinda ugly since functions aren’t first class in Java •  Looks better in Groovy THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS
  21. 32 JavaRx on Android public  static  Observable<WeatherData>  getWeatherData(final  String  city)

     {                return  Observable.create(                  new  Observable.OnSubscribeFunc<WeatherData>()  {                    @Override                    public  Subscription  onSubscribe(Observer<?  super  WeatherData>  observer)  {                                  try  {                                          observer.onNext(apiManager.getWeather(city,  "metric"));                                          observer.onCompleted();                                  }  catch  (Exception  e)  {                                          observer.onError(e);                                  }                                      return  Subscriptions.empty();                          }                  }).subscribeOn(Schedulers.threadPoolForIO());          }     THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS http://howrobotswork.wordpress.com/2013/10/28/using-rxjava-in-android/
  22. 33 JavaRx on Android Observable.from(cities)          

             .mapMany(new  Func1<String,  Observable<WeatherData>>()  {                                  @Override                                  public  Observable<WeatherData>  call(String  s)  {                                          return  ApiManager.getWeatherData(s);                                  }                          })                          .subscribeOn(Schedulers.threadPoolForIO())                          .observeOn(AndroidSchedulers.mainThread())                          .subscribe(new  Action1<WeatherData>()  {                                  @Override                                  public  void  call(WeatherData  weatherData)  {                                          //  do  your  work                                  }                          }); THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS http://howrobotswork.wordpress.com/2013/10/28/using-rxjava-in-android/
  23. 35 ReactiveCocoa •  Like KVO, •  But with Blocks • 

    And composable •  RACSignal THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS
  24. 36 ReactiveCocoa [[RACObserve(self,  username)          filter:^(NSString  *newName)

     {                  return  [newName  hasPrefix:@"j"];          }]          subscribeNext:^(NSString  *newName)  {                  NSLog(@"%@",  newName);          }]; THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS https://github.com/ReactiveCocoa/ReactiveCocoa
  25. 37 ReactiveCocoa RAC(self.imageView,  image)  =     [[[[client  fetchUserWithUsername:@"joshaber"]  

           deliverOn:[RACScheduler  scheduler]]          map:^(User  *user)  {                  //  Download  the  avatar  (this  is  done  on  a   background  queue).                  return  [[NSImage  alloc]          initWithContentsOfURL:user.avatarURL];          }]          //  Now  the  assignment  will  be  done  on  the  main   thread.          deliverOn:RACScheduler.mainThreadScheduler]; THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS https://github.com/ReactiveCocoa/ReactiveCocoa
  26. 39 Bacon.js •  EventStream •  Property •  Promise •  Bus!

    •  .onValue(function(){}) •  .merge •  .map THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS
  27. 40 Bacon.js var  minusOnes  =     $('#minusOne').asEventStream('click').map(-­‐1)   var

     plusOnes  =     $('#plusOne').asEventStream('click').map(1)     var  score  =     minusOnes.merge(plusOnes)                    .scan(0,  function(sum,  value)  {                                                  return  sum  +  value                              })   score.assign($('#score'),  'text'); THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS http://latentflip.com/bacon-talk-realtimeconfeu/
  28. 42 Conclusions •  Everyone is a winner :D •  Bus

    •  Broadcasts •  Nothing too noisy •  Programming ‘in the large’ •  Reactive •  UI •  Composing local streams •  Fire hose please! THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS
  29. 43 THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS Location

    Battery Conn Type Unique Updates Rough Time Message Bus merge filter map reduce UI Real Time
  30. 44 Really practical advice •  Don’t forget to clean up

    your subscriptions •  Consider pushing unsubscribe events •  Whole new set of bugs caused by events publishing before you’ve subscribed THE EMERGENCE OF NEW ARCHITECTURES FOR MOBILE APPS