Share
Embed
Transcript
53 slides
-
RxJava I’m Hugo Cordier CTO at Melusyn ◦ Java developer
◦ Groovy developer ◦ Javascript developer -
“Melusyn helps film makers to manage and organize their productions”
We are hiring! Drop me a line at [email protected] -
RxJava ◦ Callbacks and Futures ◦ Where is Rx from?
◦ Introducing Observable ◦ Subscribing to an Observable ◦ Applying operators ◦ Handling errors ◦ Hot and Cold Observable ◦ Backpressure ◦ Schedulers -
Rx - Callbacks server.listen(8080, "127.0.0.1", new AsyncResultHandler<Void>() { public void
handle(AsyncResult<HttpServer> asyncResult) { log.info("Listen succeeded?"+asyncResult.succeeded()); } } ); Lot of boilerplate code Hard to read A mess to chain -
Rx - CompletableFutures CompletableFuture<Customer> customerFuture = loadCustomerDetails(123); CompletableFuture<Shop> shopFuture =
closestShop(); CompletableFuture<Route> routeFuture = customerFuture.thenCombine(shopFuture, (cust, shop) -> findRoute(cust, shop) ); Easier to chain Easier to read But... -
Futures contains only 1 value We can’t deal about time
It’s hard to deal with threads -
Rx - Where’s it from ◦ Erik Meijer developed the
concepts at Microsoft ◦ Microsoft open sourced Rx.NET and RxJS in 2012 ◦ In 2013 Netflix open sourced RxJava, based on Erik Meijer concepts -
Observable - Iterable parallel Single return value Mutiple return values
Synchronous Data getData() Iterable<Data> getData() Asynchronous Future<Data> getData() Observable<Data> getData() -
Observable - Iterable parallel Data data = getData() if (data.equals(x))
{ // Do something } else { // Do something else } Single return value Mutiple return values Synchronous Data getData() Iterable<Data> getData() Asynchronous Future<Data> getData() Observable<Data> getData() -
Observable - Iterable parallel Iterable<Data> data = getData() data.forEach(value ->
{ if (value.equals(x)) { // Do something } else { // Do something else } }) Single return value Mutiple return values Synchronous Data getData() Iterable<Data> getData() Asynchronous Future<Data> getData() Observable<Data> getData() -
Observable - Iterable parallel CompletableFuture<Data> data = getData() data.thenApply(value ->
{ if (value.equals(x)) { // Do something } else { // Do something else } }) Single return value Mutiple return values Synchronous Data getData() Iterable<Data> getData() Asynchronous Future<Data> getData() Observable<Data> getData() -
Observable - Iterable parallel Observable<Data> data = getData() data.map(value ->
{ if (value.equals(x)) { // Do something } else { // Do something else } }) Single return value Mutiple return values Synchronous Data getData() Iterable<Data> getData() Asynchronous Future<Data> getData() Observable<Data> getData() -
An Observable can : • emit events (0 to ∞)
• emit an error • complete stream Once an error has been emitted, no further events can be. An Observable could be infinite. Observable - Introduction -
rx.Observable.create { observer -> try{ for (int i = 0;
i < 2; i++) { observer.onNext(i); } observer.onCompleted(); } catch (Exception e) { observer.onError(e); } } -
rx.Observable.create { observer -> executor.execute(new Runnable() { def void run()
{ try { for (int i = 0; i < 10; i++) { observer.onNext(i); this.sleep(2000) } observer.onCompleted(); } catch (Exception e) { observer.onError(e); } } }) } -
getData() .subscribe(new Subscriber() { @Override void onNext(Object o) { logger.info(o)
} @Override void onError(Throwable e) { logger.error("Oops", e) } @Override void onCompleted() { logger.debug("Stream has completed") } }) -
getData() .subscribe( { next -> logger.info(o) }, { e ->
logger.error("Oops", e)}, { logger.debug("Stream has completed")} ) -
rx.Observable.merge(getDataA(), getDataB()) .subscribe {value -> logger.info value} Live example :
http://rxmarbles.com/#merge -
rx.Observable.zip(getDataA(), getDataB(), {vA, vB -> [vA, vB] }) .subscribe {value
-> logger.info value} Live example : http://rxmarbles.com/#zip -
Let’s use swapi.co, the Star Wars API Films, Characters, Planets,
Species, everything from Star Wars :D What if I want to fetch every Character of a film, consolidated with its homeworld planet and species? Let’s try with Rx! Real life exemple -
getData() .filter {it>3} .map {it+2} .subscribe( { next -> logger.info(o)
}, { e -> logger.error("Oops", e) // Handle any error here }, { logger.debug("Stream has completed")} ) Once Observable has failed, it terminates and do not send any more events. -
Errors can be caught with Observable<T> onErrorResumeNext (Observable<? extends T>
resumeSequence) Observable<T> onErrorReturn (Func1<java.lang.Throwable,? extends T> resumeFunction) -
Cold Observables They are passive streams, producing events when subscribed
to. This is default behaviour. def source = rx.Observable .interval(1, java.util.concurrent.TimeUnit. SECONDS) .doOnEach {println "Emitted an event"} source.subscribe ( {println it}, {it.printStackTrace()} ) This part is declarative. No events are emitted until something subscribe to it At this point, source starts to emit events -
Hot Observables They are active streams, and produce events regardless
of subscription def source = rx.Observable .interval(1, java.util.concurrent.TimeUnit.SECONDS) .doOnEach {println "Emitted an event"} .publish() source.connect() source.subscribe ( {println it}, {it.printStackTrace()} ) publish() makes it a hot observable which will be triggered by connect() At this point, source starts to emit events -
Backpressure As Hot Observables emit events as their own pace,
what if it emits faster than subscriber can consume data? Backpressure allows subscriber to control the stream. Some existing operators implements backpressure : merge, zip, from, groupBy, delay, scan, ... It can be implemented in any Observable source. -
Schedulers Rx is single threaded by default Schedulers define where
to run each computation Each Operator has a default Scheduler [1] Rx allows developers to specify where to run their code using : public final Observable<T> subscribeOn(Scheduler scheduler) public final Observable<T> observeOn(Scheduler scheduler) [1] And you can find them here -
Schedulers Scheduler Purpose Schedulers.computation( ) meant for computational work such
as event- loops and callback processing; do not use this scheduler for I/O (use Schedulers.io( ) instead) Schedulers.from(executor) uses the specified Executor as a Scheduler Schedulers.immediate( ) schedules work to begin immediately in the current thread Schedulers.io( ) meant for I/O-bound work such as asynchronous performance of blocking I/O, this scheduler is backed by a thread-pool that will grow as needed; for ordinary computational work, switch to Schedulers.computation( ) Schedulers.newThread( ) creates a new thread for each unit of work Schedulers.trampoline( ) queues work to begin on the current thread after any already-queued work -
Rx World • Rx.NET • RxJava, RxScala, RxGroovy, RxJRuby, RxNetty,
RxAndroid • Rx.rb • Rx.py • RxClojure • RxCpp • RxKotlin