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.

Practical RxJava

10.506 visualizaciones

Publicado el

Recorded at SpringOne2GX 2015
Presenter: Simon Baslé
Web / Javascript Track

RxJava is an awesome library for async data streams. It is both expressive and powerful but the learning curve can be quite steep at first. So we want to quickstart developers into the world of Reactive eXtensions with more context than just listing operators!
Adapted from a hands-on workshop, this talk will describe how one can migrate code into a fully async and RxJava-based application, built upon Spring Boot and Java 8.
What kind of changes does this require? What shifts in thinking? What are the traps and pitfalls to avoid? Hopefully you'll learn the answers to these questions in this talk!

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

Practical RxJava

  1. 1. SPRINGONE2GX WASHINGTON, DC Unless otherwise indicated, these slides are © 2013-2015 Pivotal Software, Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Practical RxJava By Simon Baslé @simonbasle
  2. 2. @Couchbase
  3. 3. the Plan & Goals
  4. 4. RxJava 101
  5. 5. migrate a Legacy application RxJava 101
  6. 6. migrate a Legacy application learn Operators of interest RxJava 101
  7. 7. migrate a Legacy application learn Operators of interest 9 steps + Q&A RxJava 101
  8. 8. Why?
  9. 9. Blocking it’s Evil, m’kay?
  10. 10. Blocking it’s Evil, m’kay?
  11. 11. we need asynchronous code
  12. 12. we need reactive asynchronous code
  13. 13. we need parallelisable asynchronous code
  14. 14. we need composable asynchronous code
  15. 15. we need readable asynchronous code
  16. 16. but how ?
  17. 17. Futures<T>?Callbacks?
  18. 18. Futures<T>?Callbacks? too easy to block (get) complex beyond 1 level of composition no composition have you heared of Callback Hell?
  19. 19. DocumentService.find("userId", new Callback<List<Document>>() { public void onSuccess(List<Document> result) { final List<String> jsonList = new ArrayList<String>(10); int taken = 0; for (Document doc : result) { if (taken >= 10) break; if (!doc.isStarred()) continue; taken++; final CountDownLatch rendezVous = new CountDownLatch(3); final JsonObject jsonBuffer = new JsonObject(); jsonBuffer.appendInt("id", doc.getId()); jsonBuffer.append("text", doc.getText()); CommentService.findForDoc(doc, new Callback<List<Comment>>() { public void onSuccess(List<Comment> comments) { final JsonObject commentArray = JsonObject.createArray(); CountDownLatch userLatch = new CountDownLatch(comments.size()); for (Comment c : comments) { JsonObject cj = new JsonObject(); cj.append("content", c.getText()); cj.append("date", c.getDate()); UserService.find(c.getUserId(), new Callback<User>() { public void onSuccess(User user) { cj.append("author", user.getName()); cj.append("nickname", user.getLogin()); Futures<T>?Callbacks? too easy to block (get) complex beyond 1 level of composition no composition have you heared of Callback Hell?
  20. 20. RxJava 101
  21. 21. RxJava 101
  22. 22. Netflix OpenSource
  23. 23. dual of Iterable - Iterator
  24. 24. Iterable - Iterator becomes Observable - Observer
  25. 25. Iterable - Iterator becomes Observable - Observer “Pull” “Push”
  26. 26. compose
  27. 27. compose asynchronous programs based on events
  28. 28. compose asynchronous programs based on events using observable sequences
  29. 29. the Reactive Manifesto reactivemanifesto.org
  30. 30. reactive-streams.org standardize on the jvm
  31. 31. reactive-streams.org standardize on the jvm akka - reactor - rxjava
  32. 32. Show Me how it works !
  33. 33. interface Observer<T>
  34. 34. interface Observer<T> onNext(T data)
  35. 35. interface Observer<T> onNext(T data) onCompleted()
  36. 36. interface Observer<T> onNext(T data) onCompleted() onError(Throwable t)
  37. 37. interface Observer<T> onNext(T data) onCompleted() onError(Throwable t)
  38. 38. Observable<T>
  39. 39. Observable<T> compose & chain a stream
  40. 40. Observable<T> subscribe an Observer<T>
  41. 41. so much Choice, you’ll see!
  42. 42. still lost… time to practice
  43. 43. The Legacyapp
  44. 44. Wow pool API? Much Legacy!
  45. 45. Doge Mining Pool Client (UI?) Rest Controller Rest Controller Rest Controller Rest Controller Service Service Service External API External API External APIDB L E G A C Y (sort of)
  46. 46. Doge Mining Pool Client (UI?) Rest Controller Rest Controller Rest Controller Rest Controller Service Service Service External API External API External APIDB
  47. 47. Doge Mining Pool Client (UI?) Rest Controller Rest Controller Rest Controller Rest Controller Service Service Service External API External API External APIDB
  48. 48. simple Creation1
  49. 49. Observable Factories ● just ● from ● create
  50. 50. Map
  51. 51. Revert back to Blocking ● toBlocking ● choose what item to return (first/last/single…)
  52. 52. Single
  53. 53. SingleOrDefault
  54. 54. Transform2
  55. 55. flatMap
  56. 56. reduce
  57. 57. Filter3
  58. 58. filter
  59. 59. Take
  60. 60. takeUntil
  61. 61. Count4
  62. 62. count
  63. 63. Side Effects5
  64. 64. doOnXXX ● doOnNext ● doOnError ● doOnCompleted ● doOnEach
  65. 65. Combine6
  66. 66. Level: Simple Concat
  67. 67. Level: Intermediate Merge
  68. 68. Level: Advanced Zip
  69. 69. Live & Let Dieand Retryoo7
  70. 70. Retry
  71. 71. a note on Hot vs Cold
  72. 72. OnErrorReturn
  73. 73. Chain8
  74. 74. Useful Operators ● zipWith ○ similar to zip but called from stream A instead of statically ○ combine both rates to get the final one
  75. 75. Oh Hey! ! WARNING - Incoming Product Owner !
  76. 76. "this free exchange rate API crashes too often, make it so we switch to an alternative paid API when it’s the case" - the Product Owner
  77. 77. "this free exchange rate API crashes too often, make it so we switch to an alternative paid API when it’s the case" - the Product Owner
  78. 78. "oh yeah and if you could go on and track costs of these calls it would be great" - the Product Owner, pouring himself a coffee Much Surprise Such Requirements wow
  79. 79. The Plan ● AdminService ○ add method+variable to track cost for this month ● ExchangeRateService ○ rate retrieval method similar to current one ○ use endpoint from exchange.nonfree.api.baseUrl ● switch thanks to OnErrorResumeNext ● use side effects ○ log when we switch & track the cost
  80. 80. OnErrorResumeNext
  81. 81. Clean-up Controllers9
  82. 82. Asynchronous Response ● prepare a DeferredResult<T> ○ that will be returned without blocking ● subscribe on stream ○ onNext: inject T via setResult ○ onError: create a DogePoolException and inject it via setErrorResult
  83. 83. This could be Generalized ● using ReturnValueHandler and a simple adapter of Observable to DeferredResult ● each time an Observable is returned, it’ll be converted into this adapter ○ WebAsyncUtils.getAsyncManager(...). startDeferredResultProcessing(...)
  84. 84. Testing ● using mockMvc’s andReturn() to get a MvcResult ○ assert status().isOk() and request().asyncStarted() ● trigger the async processing ○ mockMvc.perform(asyncDispatch(mvcResult)) ● from this point assert as before
  85. 85. TakeAway
  86. 86. Nonblocking code
  87. 87. without Callbacks
  88. 88. with a minimum of visual cluter
  89. 89. readable and understandable
  90. 90. Hope you loved it!
  91. 91. Q&A
  92. 92. Unless otherwise indicated, these slides are © 2013-2015 Pivotal Software, Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ Learn More. Stay Connected. @springcentral Spring.io/video To play with the workshop: http://bit.ly/PracticalRx 93
  93. 93. ➔ RxJava Logo and Marble Diagrams - ReactiveX Documentation http://reactivex.io ➔ Cat Attack - Static416 on Flickr ➔ Stormtroopers Series - J.D. Hancock http://photos.jdhancock.com/series/stormtroopers.html ➔ Blackhole with Corona - NASA on Wikimedia ➔ Ice & Fire Showdown - HOA420 on Wikimedia ➔ Gobot Toys- Tom Prankerd on Wikimedia ➔ Coffee Filter - Unsplash on Pixabay ➔ Abacus - Succo on Pixabay ➔ Still from Office Space - Copyright, 20th Century Fox By By-Nc By Cc0 By-Sa By Cc0 Cc0 © Credits (1/2)
  94. 94. ➔ Hand Reaching - Kinseykick on Pixabay ➔ Sidecar Motocross - Jean-Daniel Echenard on Flickr ➔ Twin Falls - Blese on Flickr ➔ Tumbeast Gnawing on Servers - Matthew Inman on Wikimedia ➔ Trap - Anticiv on Flickr ➔ Kane Cleaning Supplies - Collinanderson on Flickr ➔ Chain - Stomchak on Wikimedia ➔ Takeaway - Edimburgh Blog on Flickr ➔ The End Sands - Elektro-Plan on Pixabay Cc0 By-Nd By-Nc By By-Sa By By By Cc0 Credits (2/2)

×