Post on 07-Jan-2017
Reactive Programming in Java 8 with Rx-Java
Kasun IndrasiriSoftware Architect, WSO2
January 2016
Why Reactive Programming? • Why another programming paradigm? • Things are different now! • Conventional software applications won’t be able to fulfill the
modern enterprise needs. • Its time to rethink about our software architecture patterns and
programming techniques.
What it actually means to be Reactive?• “Readily responsive to a stimulus” - merriam-webster
• Reactive Systems :• responds in a timely manner • stays responsive in the face of failure• stays responsive under varying workload• rely on asynchronous message-passing
Reactive Programming• A programming paradigm that helps you to build
‘Reactive Systems’. E.g.: Google Spreadsheet• In a reactive world, we can't just wait for a function
result, a network call, or a database query to return. • Every moment we wait for something, we lose the
opportunity to do other things in parallel. • Reactive programming can be done in several ways• Akka Actors• Reactive Extensions (Rx) – reactive + functional
Why Rx-Java? • The Netflix story..
The Netflix API • How to reducing network chattiness? • Granular API. • client applications to make multiple calls that need to be assembled in order
to render a single user experience
The Netflix API • Discrete requests from devices, should be collapsed into
a single request• Server-side concurrency is needed to effectively reduce
network chattiness.• Nested, conditional, parallel execution of backend
network calls.
Embrace Concurrency• Blocking calls?... Not anymore. • Server-side concurrency is a must. • Low level primitive of concurrency. • Concurrent programming is hard!
Java Futures• Represents the result of an asynchronous computation.• Can be used to retrieve the result asynchronously at a
later point in time• Cons: • Retrieving value from future is a blocking call : Future.get()• Messy with Nested Futures -> complex to implement/maintain.
Callbacks• A callback is a piece of executable code that is passed as
an argument to other code, which is expected to call back the argument at some convenient time.
Callbacks• Use case : • Client send a request to the Application • Application calls service A• Get the response from ServiceA and send it to service B• Get the response from ServiceB and send it to Service C• Get the response from ServiceC and send it to the Client
Service A
Service B
Service C
1
2
3
ApplicationClient
Callbacks• Callback Hell!• Callbacks based applications get extremely complex when we have nested
callbacks. • Leads to messy code, hard to troubleshoot. • Example : https://github.com/kasun04/rnd/tree/master/rx-java/src/main/java/org/kasun/
rnd/rxjava/serviceinvoker/callback
Reactive Extensions - Rx• ReactiveX is a library for composing asynchronous and
event-based programs by using observable sequences.• ‘The Observer pattern done right.’ • Initially implemented for C# by Microsoft, later ported to
many languages by Netflix Rx. • Rx-Java is the Java implementation.
Observer Pattern• ‘Subject’ notifies the ‘observers’ when a change has
happened in the subject.
Observable • Rx-Java introduces ‘Observable’ data type by extending
the traditional Observer Pattern.
Observers
Observable
Observable vs Observer Pattern • The producer signal that there is no more data available:
the• onCompleted() event
• The producer can signal that an error occurred• onError() event
Observable and Subscriber • The producer signal that there is no more data available:
the
ObservableSubscriber
subscribe
onNext*
onCompleted
Observable and Subscriber – In Action
Creating Observable • Observable.create()• Observable.just()• Observable.from()
Observable and Operators • Observable -> Operator -> Subscriber
Filtering Observables• Selectively emit items from a source Observable
Filtering Observables• Filtering Operators
Transforming Observables• Transform items that are emitted by an Observable
Transforming Observables• Transforming Operators
Filtering and Transforming – In Action
Transforming Observables• FlatMap• Observable.flatMap() takes the emissions of one Observable and returns the
emissions of another Observable to take its place.
Observable<List<String>> query(String text){...}
query("Hello, world!") .flatMap(new Func1<List<String>, Observable<String>>() { @Override public Observable<String> call(List<String> urls) { return Observable.from(urls); } }) .subscribe(url -> System.out.println(url));
FlatMap – In Action
More Operators • Combining Observables• Error Handling Operators• Observable Utility Operators• Conditional and Boolean Operators
http://reactivex.io/documentation/operators.html
Rx-Java in Action • Use case : Service Orchestration
Source Code : https://github.com/kasun04/rnd/tree/master/rx-java/src/main/java/org/kasun/rnd/rxjava/serviceinvoker/rx/nonblocking
Service A
Service B
Service C
1
2
3
ApplicationClient
Scheduler• Rx is single threaded by default. • Schedulers are the easiest way to bring multi-threading
into your apps.• subscribeOn• observerOn
Scheduler• Schedulers.io(): meant for I/O-bound work• Schedulers.computation(): meant for computational
work such as event-loops • Schedulers.newThread(): creates a new thread for
each unit of work
Rx-Java in Action • Use case : Service Orchestration with Schedulers
Source Code : https://github.com/kasun04/rnd/tree/master/rx-java/src/main/java/org/kasun/rnd/rxjava/serviceinvoker/rx/nonblocking
Service A
Service B
Service C
1
2
3
ApplicationClient
Conclusion• Get rid of blocking code! • Think ‘non-blocking’ • Think reactive • Rx-Java – steep learning curve • Develop use cases• Leverage Java 8
Questions?
References • http://reactivex.io/documentation• http://blog.danlew.net/2014/09/15/grokking-rxjava-part
-1/• http://techblog.netflix.com/2013/02/rxjava-netflix-
api.html• Source Code :
https://github.com/kasun04/rnd/tree/master/rx-java
Thank You