Se ha denunciado esta presentación.
Utilizamos tu perfil de LinkedIn y tus datos de actividad para personalizar los anuncios y mostrarte publicidad más relevante. Puedes cambiar tus preferencias de publicidad en cualquier momento.

Reactive in Android and Beyond Rx

192 visualizaciones

Publicado el

The word "Reactive" can be confusing. As the founder of the Reactive Amsterdam meetup, I can tell there are two main topics here: Functional Reactive Programming (here with reference to Android) and "Reactive" in the sense of the Reactive Manifesto.

Publicado en: Tecnología
  • Sé el primero en comentar

  • Sé el primero en recomendar esto

Reactive in Android and Beyond Rx

  1. 1. Reactive in Android & beyond Rx Fabio Tiriticco / @ticofab DAUG Meetup 23 August 2016
  2. 2. A little info about myself Android Engineer Backend Architect
  3. 3. The Reactive Amsterdam meetup Reactive Amsterdam • cross-technology • cross-domain
  4. 4. “Reactive” in the vocabulary Reactive (adjective): Tending to act in response to an agent or influence
  5. 5. Reactive Confusion Functional Reactive Programming Reactive in the context of the “Reactive Manifesto” OR
  6. 6. Reactive Programming
  7. 7. Why Functional? More supportive of reasoning about problems in concurrent and parallelised applications. • encourages use of pure functions - minimise side effects • encourages immutability - state doesn’t get passed around • higher-order functions - reusability and composability
  8. 8. Hello, RxJava! Mobile engineering is hard and there are high expectations. RxJava is cool because • it makes it super easy to switch between threads • lets us deal with data as a stream • brings us some degree of functional programming
  9. 9. Hello, RxJava! RxJava RxJs RxClojure RxSwift … • Asynchronous programming • Observable streams Open source libraries for
  10. 10. RxJava goes hand in hand with Java8’s Lambdas new Func1<String, Integer>() { @Override public Integer call(String s) { return s.length(); } } (String s) -> { return s.length(); } s -> s.length(); Retrolamba plugin for Android < N
  11. 11. RxJava: dealing with a stream of items class Cat { ... public String getName() public Color getColor() public Picture fetchPicture() ... }
  12. 12. RxJava: dealing with a stream of items Observable.from(myCats); cat -> Timber.d(cat.getName()) List<Cat> myCats; Observable obs = obs.subscribe( ); Observable.from(myCats) .subscribe(cat -> Timber.d(cat.getName()));
  13. 13. RxJava: work on the stream Observable.from(myCats) .subscribe(color -> Timber.d(color)); map: function that takes T => outputs R .map( )cat -> cat.getColor()
  14. 14. RxJava: operators to manipulate the stream Observable.from(myCats) .distinct() .delay(2, TimeUnit.SECONDS) .filter(cat -> cat.getColor().isWhite()) .map(cat -> cat.getName()) .subscribe(name -> Timber.d(“a unique, delayed white cat called ” + name));
  15. 15. Observable.from(myCats) .subscribe( cat -> Timber.d(cat.getName()), error -> error.printStackTrace(), () -> Timber.d(“no more cats”) ); RxJava: subscriber interface Observable.from(myCats) .subscribe( onNext<T>, // next item T onError, // throwable onComplete // void );
  16. 16. Observable.from(myCats) .subscribe(cat -> Timber.d(“cat”)); RxJava: unsubscribe Subscription subs = subs.unsubscribe();
  17. 17. RxJava: threading Observable.from(myCats) .map(cat -> cat.fetchPicture()) .map(picture -> Filter.applyFilter(picture)) .subscribe( filteredPicture -> display(filteredPicture) ); .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread())
  18. 18. RxJava: other ways of creating Observables // emits on single item and completes Observable.just // emits one item after a certain delay Observable.timer // emits a series of integers at regular pace Observable.interval .. plus many others, and you can create your own — BUT TRY NOT TO -
  19. 19. RxJava: a few disadvantages • debugging is more difficult • methods with side effects • powerful abstraction - lot of stuff under the hood
  20. 20. RxJava: demo with Retrofit & Meetup Streams http://stream.meetup.com/2/rsvp Meetup Streaming API
  21. 21. RxJava: demo with Meetup Streams
  22. 22. RxJava: demo with Retrofit & Meetup Streams interface MeetupAPI { @GET("http://stream.meetup.com/2/rsvp") @Streaming Observable<ResponseBody> meetupStream(); }
  23. 23. RxJava: demo with RSVP Meetup Streams meetupAPI.meetupStream() ... .flatMap(responseBody -> events(responseBody.source())) .map(string -> gson.fromJson(string, RSVP.class)) ... .subscribe(rsvp -> ...); map: T => R flatMap: T => Observable<R>
  24. 24. RxJava: demo with Meetup Streams
  25. 25. RxJava: demo with Meetup Streams https://github.com/ticofab/android-meetup-streams
  26. 26. 2006 2016 Servers ~10 The sky is the limit. Response time seconds milliseconds Offline maintenance hours what? Data amount Gigabytes Petabytes Machines Single core, little distribution Must work across async boundaries (location, threads) Kind of data Request - response Streams (endless) Reactive in the sense of the Reactive Manifesto
  27. 27. Evolution of internet usage
  28. 28. The Reactive traits A reactive computer system must Trait React to its users Responsive React to failure and stay available Resilient React to varying load conditions Elastic Its components must react to inputs Message-driven
  29. 29. Reactive traits: Responsive • A human who visits a website • A client which makes a request to a server • A consumer which contacts a provider • . . . A Reactive system responds to inputs and usage from its user.
  30. 30. Reactive traits: Elastic • Scale OUT and IN: use just the right amount • Elasticity relies on distribution • Ensure replication in case of failure Scale on demand to react to varying load
  31. 31. Reactive traits: Resilient It doesn't matter how great your application is if it doesn't work. FAULT TOLERANCE RESILIENCEVS
  32. 32. Reactive traits: Message Driven Reactive systems design concentrates on Messages. Asynchronous messaging enables: • Separation between components • Error containment - avoid chain failures • Domain mapping closer to reality
  33. 33. The Reactive Manifesto
  34. 34. Reactive Patterns Design patterns to achieve Reactive principles. Toolkits exist to implement these patterns.
  35. 35. Reactive Pattern: Simple Component Pattern “One component should do only one thing but do it in full. The aim is to maximise cohesion and minimise coupling between components.”
  36. 36. Reactive Pattern: Simple Component Pattern Actor 1 Actor 3 Actor 2 • contains state • has a mailbox to receive and send messages • contains behaviour logic • has a supervisor Actor model Supervisor
  37. 37. Example: Synchronous DB access Activity DB service DB List<Cat> cats = new ArrayList<Cat>(); try { cats = dbService.getAllCats(); } catch (ExampleException e) { // TODO }
  38. 38. Example: DB access with callback dbService.getAllCats(new OnCompleted() { @Override public void onDataRetrieved(List<Cat> cats) { // TODO } }); Activity DB service DB
  39. 39. Example: Async Messaging with Actors Activity actor DB Actor DB
  40. 40. Example: Async Messaging with Actors - messages // message to ask for cats public class GetCats { } // message to send results back public class Results { ArrayList<Cat> mCats; public Results(ArrayList<Cat> cats) { mCats = cats; } }
  41. 41. Example: Async Messaging with Actors - behaviour // db actor pseudocode @Override public void onReceive(Message message) { } if (message is GetCats) { } // retrieve cats from database c = contentResolver.query(...) ... // send cats to the Activity Results result = new Results(cats); activityAddress.tell(result)
  42. 42. Reactive Patterns: Let it crash! "Prefer a full component restart to complex internal failure handling". • failure conditions WILL occur • they might be rare and hard to reproduce • it is much better to start clean than to try to recover • …which might be expensive and difficult!
  43. 43. Reactive Patterns: Let it crash! Actor supervision example Actor 1 Actor 2 Supervisor WhateverException! X Fix or Restart
  44. 44. Reactive Patterns: Let it crash! • the machine only accepts exact change
  45. 45. Reactive Patterns: Let it crash! Scenario 1: The user inserts wrong amount of coins X Error
  46. 46. Reactive Patterns: Let it crash! Scenario 2: The machine is out of coffee beans Failure ( != error)
  47. 47. Reactive Patterns: Let it crash!
  48. 48. Recap • Tried to clarify the Reactive Confusion • Examples of FRP in Android • Reactive principles from the Reactive Manifesto • A couple of Design Patterns to achieve them • (with a glimpse of pseudo implementation) Reactive Amsterdam
  49. 49. Thanks! @ticofab All pictures belong to their respective authors AMSTERDAM 11-12 MAY 2016
  50. 50. Resources https://github.com/ReactiveX/RxJava/wiki RxJava documentation & wiki http://rxmarbles.com RxJava operators explained visually http://www.reactivemanifesto.org The reactive manifesto https://www.youtube.com/watch?v=fNEZtx1VVAk https://www.youtube.com/watch?v=ryIAibBibQI https://www.youtube.com/watch?v=JvbUF33sKf8 The Reactive Revealed series: awesome webinars by the creators of the Reactive Manifesto. https://www.manning.com/books/reactive-design-patterns https://www.youtube.com/watch?v=nSfXcSWq0ug Reactive design patterns, book and webinar.

×