Building Scalable Stateless Applications with RxJava

  • Published on
    06-Jul-2015

  • View
    984

  • Download
    1

DESCRIPTION

RxJava is a lightweight open-source library, originally from Netflix, that makes it easy to compose asynchronous data sources and operations. This presentation is a high-level intro to this library and how it can fit into your application.

Transcript

<ul><li> 1. Building Scalable Stateless Applications with RxJavaRick Warren | Principal Engineer, eHarmonyrwarren@eharmony.com | @DangerLemming</li></ul> <p> 2. RxJava Encapsulates data sequences: Observable Provides composable operations on them Abstracts away threading and synch Port from Microsoft .NET Reactive Extensions Java 6+, Groovy, Clojure, JRuby, Kotlin, andScala; Android-compatible 3. NetflixClient Client Client Client ClientCoarse-Grained APIOrchestration LayerMi- -cro Ser- -vic- -es 4. ApplicabilityApplication or Presentation-Layer ServiceClient Client Client Client ClientDataSourceDataSourceDataSourceDataSourceDataSource 5. 3 Problems1. Streaming queries2. Rate-limited APIs(with retries)3. Using Futures 6. Streaming QueriesDataStore Service Client1 2 31. Query lots of data from NoSQL store2. Enrich, filter, and score on the fly3. Deliver best results to client 7. Streaming Queries1Query2Enrich3Deliver+ =Too Much Latency 8. Streaming Queries1Query&amp;&amp; =2Enrich3DeliverMore Efficient 9. Streaming QueriesIterablesDataStore ClientReadEnrichDrainScore Iterator pattern for fast start and lower footprint Composed as Decorators for flexibility Limitation: Doesnt abstract timing, concurrency 10. Rate-Limited APIsScenario: Ingest data frompublic APIthey will refuserapid requests!YouTube,Facebook,etc.YourService 11. Rate-Limited APIsYouTube,Facebook,etc.YourServiceInsight: The module responsiblefor what data is availableis also responsiblefor when data is available 12. Rate-Limited APIsYouTube,Facebook,etc.YourServiceSolution: Facade API withaugmented Visitors toencapsulate timing and retriesinterfaceDataVisitorextendsjava.io.Closeable{voidaccept(Tdata);}Limitation: Schedulingdoesn't generalize 13. Using Futuresjavax.ws.rs.client.InvocationResponseinvoke()Futuresubmit() API and implementation cluttered with concurrency variants Caller responsible for concurrency, but has least information What can you do with a Future besides block? 14. Using FuturesWhat about Guavas ListenableFuture?ListeningExecutorServiceservice=MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));ListenableFutureexplosion=service.submit(newCallable(){publicExplosioncall(){returnpushBigRedButton();}});Futures.addCallback(explosion,newFutureCallback(){publicvoidonSuccess(Explosionexplosion){walkAwayFrom(explosion);}publicvoidonFailure(Throwablethrown){battleArchNemesis();}}); Requires access to ExecutorService! Still hard to compose Doesnt generalize to multiple results 15. Make ItWorkInteractions should: Support multiple values Be efficient &amp; incremental Encapsulate timing Compose operations 16. RxJava: Observable LikeIterable,but offersfluent chainingoperations Like Stream,but supportsasynctermination anderror handling 17. Iterable Exampletry{for(Eelem:elements){onNext(elem);}onCompleted();}catch(Throwableex){onError(ex);} 18. Iterable Exampletry{elements.forEach(elem-&gt;onNext(elem));onCompleted();}catch(Throwableex){onError(ex);}First-classVisitor(Consumer) 19. Stream Exampletry{elements.parallelStream()Parallelizeoperations.filter(condition).map(transformation).forEach(elem-&gt;onNext(elem));onCompleted();}catch(Throwableex){onError(ex);}Still serial 20. Observable Exampleelements.filter(condition).map(transformation).subscribe(elem-&gt;onNext(elem),ex-&gt;onError(ex),()-&gt;onCompleted());Fullyasyncable 21. Creating an Observableimportrx.*;Observableo=Observable.just("a","b","c");Iterableit=ImmutableList.of("a","b","c");Observableo=Observable.from(it);Futuref=exec.submit(myTask);Observableo=Observable.from(f,Schedulers.from(exec)); 22. Example: JDBCpublicfinalclassObservableDB{privatefinalDataSourcedb;publicObservableDB(finalDataSourcesource){this.db=Objects.requireNonNull(source);}/**EachemittedListrepresentsarowintheResultSet.*/publicObservable&gt;select(finalStringsql,finalIterableparams){returnObservable.create(newObservable.OnSubscribe&gt;(){@Overridepublicvoidcall(finalSubscriber</p>

Recommended

View more >