SlideShare a Scribd company logo
Reactive Programming in Java 8
with Rx-Java
Kasun Indrasiri
Software 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

More Related Content

What's hot (20)

GraphQL vs REST
GraphQL vs REST
GreeceJS
 
React native
React native
Mohammed El Rafie Tarabay
 
Reactive Programming and RxJS
Reactive Programming and RxJS
Denis Gorbunov
 
Actor Model Akka Framework
Actor Model Akka Framework
Harinath Krishnamoorthy
 
코틀린 멀티플랫폼, 미지와의 조우
코틀린 멀티플랫폼, 미지와의 조우
Arawn Park
 
JavaScript Promises
JavaScript Promises
Derek Willian Stavis
 
TypeScript Best Practices
TypeScript Best Practices
felixbillon
 
Redux workshop
Redux workshop
Imran Sayed
 
PostgreSQL and JDBC: striving for high performance
PostgreSQL and JDBC: striving for high performance
Vladimir Sitnikov
 
Gradle Introduction
Gradle Introduction
Dmitry Buzdin
 
React new features and intro to Hooks
React new features and intro to Hooks
Soluto
 
JVM++: The Graal VM
JVM++: The Graal VM
Martin Toshev
 
Introduction to React JS
Introduction to React JS
Bethmi Gunasekara
 
Nodejs functions & modules
Nodejs functions & modules
monikadeshmane
 
Introduction to docker
Introduction to docker
Walid Ashraf
 
NodeJS for Beginner
NodeJS for Beginner
Apaichon Punopas
 
Introduction to Spring Boot
Introduction to Spring Boot
Purbarun Chakrabarti
 
Intro to react native
Intro to react native
ModusJesus
 
Quarkus tips, tricks, and techniques
Quarkus tips, tricks, and techniques
Red Hat Developers
 
NextJS, A JavaScript Framework for building next generation SPA
NextJS, A JavaScript Framework for building next generation SPA
Pramendra Gupta
 
GraphQL vs REST
GraphQL vs REST
GreeceJS
 
Reactive Programming and RxJS
Reactive Programming and RxJS
Denis Gorbunov
 
코틀린 멀티플랫폼, 미지와의 조우
코틀린 멀티플랫폼, 미지와의 조우
Arawn Park
 
TypeScript Best Practices
TypeScript Best Practices
felixbillon
 
PostgreSQL and JDBC: striving for high performance
PostgreSQL and JDBC: striving for high performance
Vladimir Sitnikov
 
React new features and intro to Hooks
React new features and intro to Hooks
Soluto
 
Nodejs functions & modules
Nodejs functions & modules
monikadeshmane
 
Introduction to docker
Introduction to docker
Walid Ashraf
 
Intro to react native
Intro to react native
ModusJesus
 
Quarkus tips, tricks, and techniques
Quarkus tips, tricks, and techniques
Red Hat Developers
 
NextJS, A JavaScript Framework for building next generation SPA
NextJS, A JavaScript Framework for building next generation SPA
Pramendra Gupta
 

Similar to Reactive Programming in Java 8 with Rx-Java (20)

RxJava - introduction & design
RxJava - introduction & design
allegro.tech
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on Android
Fernando Cejas
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJava
NexThoughts Technologies
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJava
Mike Nakhimovich
 
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
Codemotion
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
Mario Fusco
 
Streams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to Rx
Andrzej Sitek
 
rx-java-presentation
rx-java-presentation
Mateusz Bukowicz
 
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
Codemotion
 
Microservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive Programming
Araf Karsh Hamid
 
Rx presentation
Rx presentation
Ali Mahfud
 
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Introduction to RxJava on Android
Introduction to RxJava on Android
Chris Arriola
 
Functional reactive programming
Functional reactive programming
Araf Karsh Hamid
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJava
Ali Muzaffar
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
Rick Warren
 
RxJava 2 Reactive extensions for the JVM
RxJava 2 Reactive extensions for the JVM
Netesh Kumar
 
RxJava@DAUG
RxJava@DAUG
Maxim Volgin
 
Reactive programming with rx java
Reactive programming with rx java
CongTrung Vnit
 
Sperasoft Talks: RxJava Functional Reactive Programming on Android
Sperasoft Talks: RxJava Functional Reactive Programming on Android
Sperasoft
 
RxJava - introduction & design
RxJava - introduction & design
allegro.tech
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on Android
Fernando Cejas
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJava
NexThoughts Technologies
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJava
Mike Nakhimovich
 
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
Codemotion
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
Mario Fusco
 
Streams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to Rx
Andrzej Sitek
 
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
Mario Fusco - Reactive programming in Java - Codemotion Milan 2017
Codemotion
 
Microservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive Programming
Araf Karsh Hamid
 
Rx presentation
Rx presentation
Ali Mahfud
 
Introduction to RxJava on Android
Introduction to RxJava on Android
Chris Arriola
 
Functional reactive programming
Functional reactive programming
Araf Karsh Hamid
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJava
Ali Muzaffar
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
Rick Warren
 
RxJava 2 Reactive extensions for the JVM
RxJava 2 Reactive extensions for the JVM
Netesh Kumar
 
Reactive programming with rx java
Reactive programming with rx java
CongTrung Vnit
 
Sperasoft Talks: RxJava Functional Reactive Programming on Android
Sperasoft Talks: RxJava Functional Reactive Programming on Android
Sperasoft
 
Ad

More from Kasun Indrasiri (17)

Microservices Integration Patterns with Kafka
Microservices Integration Patterns with Kafka
Kasun Indrasiri
 
Adaptive and Iterative Integration for Microservices and Cloud Native Archite...
Adaptive and Iterative Integration for Microservices and Cloud Native Archite...
Kasun Indrasiri
 
Microservices for Enterprises
Microservices for Enterprises
Kasun Indrasiri
 
Bridging Microservices, APIs and Integration
Bridging Microservices, APIs and Integration
Kasun Indrasiri
 
Integration Microservices
Integration Microservices
Kasun Indrasiri
 
The Role of Enterprise Integration in Digital Transformation
The Role of Enterprise Integration in Digital Transformation
Kasun Indrasiri
 
Deep-dive into WSO2 ESB 5.0
Deep-dive into WSO2 ESB 5.0
Kasun Indrasiri
 
Microintegration
Microintegration
Kasun Indrasiri
 
Microservices in Practice
Microservices in Practice
Kasun Indrasiri
 
WSO2-ESB - The backbone of Enterprise Integration
WSO2-ESB - The backbone of Enterprise Integration
Kasun Indrasiri
 
Introduction to WSO2 Integration Platform
Introduction to WSO2 Integration Platform
Kasun Indrasiri
 
WSO2 Gateway
WSO2 Gateway
Kasun Indrasiri
 
The Middleware technology that connects the enterprise
The Middleware technology that connects the enterprise
Kasun Indrasiri
 
API, Integration, and SOA Convergence
API, Integration, and SOA Convergence
Kasun Indrasiri
 
The Past, Present and Future of Enterprise Integration
The Past, Present and Future of Enterprise Integration
Kasun Indrasiri
 
WSO2 ESB - The Backbone of Integration
WSO2 ESB - The Backbone of Integration
Kasun Indrasiri
 
Connected Retail
Connected Retail
Kasun Indrasiri
 
Microservices Integration Patterns with Kafka
Microservices Integration Patterns with Kafka
Kasun Indrasiri
 
Adaptive and Iterative Integration for Microservices and Cloud Native Archite...
Adaptive and Iterative Integration for Microservices and Cloud Native Archite...
Kasun Indrasiri
 
Microservices for Enterprises
Microservices for Enterprises
Kasun Indrasiri
 
Bridging Microservices, APIs and Integration
Bridging Microservices, APIs and Integration
Kasun Indrasiri
 
Integration Microservices
Integration Microservices
Kasun Indrasiri
 
The Role of Enterprise Integration in Digital Transformation
The Role of Enterprise Integration in Digital Transformation
Kasun Indrasiri
 
Deep-dive into WSO2 ESB 5.0
Deep-dive into WSO2 ESB 5.0
Kasun Indrasiri
 
Microservices in Practice
Microservices in Practice
Kasun Indrasiri
 
WSO2-ESB - The backbone of Enterprise Integration
WSO2-ESB - The backbone of Enterprise Integration
Kasun Indrasiri
 
Introduction to WSO2 Integration Platform
Introduction to WSO2 Integration Platform
Kasun Indrasiri
 
The Middleware technology that connects the enterprise
The Middleware technology that connects the enterprise
Kasun Indrasiri
 
API, Integration, and SOA Convergence
API, Integration, and SOA Convergence
Kasun Indrasiri
 
The Past, Present and Future of Enterprise Integration
The Past, Present and Future of Enterprise Integration
Kasun Indrasiri
 
WSO2 ESB - The Backbone of Integration
WSO2 ESB - The Backbone of Integration
Kasun Indrasiri
 
Ad

Recently uploaded (20)

Integrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FME
Safe Software
 
Advanced Token Development - Decentralized Innovation
Advanced Token Development - Decentralized Innovation
arohisinghas720
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
Maharshi Mallela
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
AI-Powered Compliance Solutions for Global Regulations | Certivo
AI-Powered Compliance Solutions for Global Regulations | Certivo
certivoai
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Microsoft Business-230T01A-ENU-PowerPoint_01.pptx
Microsoft Business-230T01A-ENU-PowerPoint_01.pptx
soulamaabdoulaye128
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Open Source Software Development Methods
Open Source Software Development Methods
VICTOR MAESTRE RAMIREZ
 
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
BradBedford3
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
UPDASP a project coordination unit ......
UPDASP a project coordination unit ......
withrj1
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
What is data visualization and how data visualization tool can help.pdf
What is data visualization and how data visualization tool can help.pdf
Varsha Nayak
 
Step by step guide to install Flutter and Dart
Step by step guide to install Flutter and Dart
S Pranav (Deepu)
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Integrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FME
Safe Software
 
Advanced Token Development - Decentralized Innovation
Advanced Token Development - Decentralized Innovation
arohisinghas720
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
Maharshi Mallela
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
AI-Powered Compliance Solutions for Global Regulations | Certivo
AI-Powered Compliance Solutions for Global Regulations | Certivo
certivoai
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Microsoft Business-230T01A-ENU-PowerPoint_01.pptx
Microsoft Business-230T01A-ENU-PowerPoint_01.pptx
soulamaabdoulaye128
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Open Source Software Development Methods
Open Source Software Development Methods
VICTOR MAESTRE RAMIREZ
 
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
BradBedford3
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
UPDASP a project coordination unit ......
UPDASP a project coordination unit ......
withrj1
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
What is data visualization and how data visualization tool can help.pdf
What is data visualization and how data visualization tool can help.pdf
Varsha Nayak
 
Step by step guide to install Flutter and Dart
Step by step guide to install Flutter and Dart
S Pranav (Deepu)
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 

Reactive Programming in Java 8 with Rx-Java

  • 1. Reactive Programming in Java 8 with Rx-Java Kasun Indrasiri Software Architect, WSO2 January 2016
  • 2. 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.
  • 3. 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
  • 4. 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
  • 5. Why Rx-Java? • The Netflix story..
  • 6. 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
  • 7. 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.
  • 8. Embrace Concurrency • Blocking calls?... Not anymore. • Server-side concurrency is a must. • Low level primitive of concurrency. • Concurrent programming is hard!
  • 9. 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.
  • 10. 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.
  • 11. 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
  • 12. 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
  • 13. 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.
  • 14. Observer Pattern • ‘Subject’ notifies the ‘observers’ when a change has happened in the subject.
  • 15. Observable • Rx-Java introduces ‘Observable’ data type by extending the traditional Observer Pattern. Observers Observable
  • 16. 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
  • 17. Observable and Subscriber • The producer signal that there is no more data available: the ObservableSubscriber subscribe onNext* onCompleted
  • 18. Observable and Subscriber – In Action
  • 19. Creating Observable • Observable.create() • Observable.just() • Observable.from()
  • 20. Observable and Operators • Observable -> Operator -> Subscriber
  • 21. Filtering Observables • Selectively emit items from a source Observable
  • 23. Transforming Observables • Transform items that are emitted by an Observable
  • 25. Filtering and Transforming – In Action
  • 26. 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));
  • 27. FlatMap – In Action
  • 28. More Operators • Combining Observables • Error Handling Operators • Observable Utility Operators • Conditional and Boolean Operators http://reactivex.io/documentation/operators.html
  • 29. 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
  • 30. Scheduler • Rx is single threaded by default. • Schedulers are the easiest way to bring multi-threading into your apps. • subscribeOn • observerOn
  • 31. 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
  • 32. 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
  • 33. Conclusion • Get rid of blocking code! • Think ‘non-blocking’ • Think reactive • Rx-Java – steep learning curve • Develop use cases • Leverage Java 8
  • 35. 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