SlideShare a Scribd company logo
1 of 28
Creating and using an
Observable with
RxJava.
Save 42% off Modern Java in
Action with code slurma at
manning.com
Both the Observable and Flowable classes come with
tons of convenient factory methods to create many
different types of reactive streams. The simplest
Observable that you may want to create is one that is
made of a fixed number of predetermined elements.
An example of an observable that emits a fixed number of
predetermined elements:
Observables
The just factory method converts one or more elements
into an Observable that emits those elements. Another
Observable that is quite common, especially when time
is a relevant factor in your application, is one that emits
events at a fixed time rate.
An example of an Observable that emits a sequence of
ascending longs, one per second:
Observables
The interval factory method returns in fact an
Observable that emits an infinite sequence of ascending
longs, with a constant interval of time of your choosing
(one second In the former example) between emissions.
We can try to use the Observable defined in the
previous slide as the basis to create another Observable
that emits the temperature detected in a given town each
second.
As an intermediate step to reach this goal, let's start with
the simpler task of printing those temperatures each
second.
Observables
To track our temperatures by the second, we need to
subscribe to an Observable in order to be notified by it
every time a second is passed and then fetch and print the
temperature of the town of our interest. In RxJava, the
Observable plays the role of the Publisher in the Flow
API, so the Observer corresponds to the Flow's
Subscriber interface.
The Observer Interface
With RxJava’s API it is possible to subscribe an
Observable with an Observer that implements only the
onSubscribe method with a consumer of the received
event, leaving the others undefined. By leveraging this
feature it is possible to subscribe to the Observable
defined in the listing and print the temperatures in New
York once a second.
Here’s what it looks like:
Subscribing to an Observable
There is an issue with the statement on the previous slide
- the Observable emits one event per second and then
the subscriber fetches the temperature in New York every
second and prints it. Indeed, if you put this statement in a
main and try to execute it you will see … nothing.
This is because the Observable publishing an event per
second is executed in a thread of RxJava's computation
thread pool, and the main thread then terminates
immediately.
Subscribing to an Observable
We can prevent this immediate termination simply by
putting a thread sleep after this statement from slide 6:
Doing so might give us the following output:
Troubleshooting our Observable
Now, since our Observer only implements the happy path
and doesn't have any sort of error management, this will
eventually blow up in our user's face.
So let’s raise the bar a bit by adding error management,
and generalizing what we have: we don't want to
immediately print the temperatures, but provide to our
user a factory method that returns an Observable
emitting those temperatures once a second for at most 5
times before completing.
Improving our Observable
We can do this by using another factory method, named
create, that instances an Observable from a lambda
taking another Observer as its argument and returning
void.
This will make our Observable function better – i.e. the
way we want it to!
On the next slide you can see our new Observable.
Improving our Observable
Improving our Observable
In the previous slide we created the returned an
Observable from a function that consumes an Observer
sending to it the desired events.
Internally we are subscribing on an Observable
publishing an infinite sequence of ascending longs, one per
second, in order to have a timer that emits an event each
second.
At this point it is easy to implement a complete
Observer that subscribes to the Observable returned
by this method and printing the temperatures published
by it.
Refining our Observable
Here’s our Observable printing out
received temperatures:
Our Observable in Action
We are now ready to create a main where we subscribe
this Observer to the Observable returned by the
method of slide 10 in order to print the temperatures in
New York.
Creating a main
It turned out to be necessary to add a sleep at the end of
the main method because the Observable works in a
thread of RxJava's pool and we need to give it time to
perform its job.
As long as there isn’t an error while fetching the
temperatures, the main will print a line per second for 5
times and then the Observable will emit the complete
signal, so we might get an output like the following:
Creating a main
Let’s take our RxJava example a bit further to show how
this library allows manipulation of one or more reactive
streams.
One of the main advantages of RxJava and other reactive
libraries, while working with reactive streams (compared
with what is offered by the native Java Flow API), is that
they provide a rich toolbox of functions to combine,
create, and filter any of those streams.
Manipulating reactive streams
We’ve seen a stream getting used as an input to another
one, but it is also possible to filter a stream to get another
one that has only those elements you are interested in,
transform those elements with a given mapping function,
or even merge or combine two streams in many different
ways.
To overcome the problem of explaining function behavior
in plain words –which often comes out rather cryptic– the
reactive streams community documents functions using
marble diagrams.
Manipulating reactive streams
A marble diagram
Using this type of notation it's easy to provide a visual
representation of the features of all of RxJava's
functions, like map and merge (shown below) or a
typical Observer like on the previous slide.
A marble diagram
So how can we put these two functions to use with
our thermometer example? First, let’s put map to
work converting from Fahrenheit to Celsius,
previously implemented using the Flow API's
Processor.
This simple method takes the Observable returned
by our getTemperature from slide 10 and converts
the temperatures to Celsius.
Putting it all together
Now, let’s imagine that we need to emit temps for a
group of towns, rather than one. We can perform the
method from the previous slide for each town and
combine the Observables together using the
merge function.
This method takes a varargs, containing the set of
towns for which we are emitting temps, as an
argument.
Putting it all together
The varargs gets put into a Stream of String, and then
each String is passed to the method from slide 18.
Basically, each town is transformed into an Observable
emitting a temperature every second. In the end, the
Stream of Observables is collected into a List and the List
is passed to the merge static factory method provided by
the Observable class itself. This method takes an
Iterable of Observables and combines their output so
they act like a single Observable.
Pretty cool!
Putting it all together
Let's also try to put this last method at work by using it in
one last main class.
Putting it all together
You might have noticed that this last main class is nearly
identical to the one from slide 13, but this one is now
subscribing to the Observable returned by the method in
slide 19 and printing the temperatures registered in 3
different towns.
When run, it should give an output like this:
Putting it all together
As you can see, each second it prints the temperatures of
each of the requested towns until one of the temperature
fetching operations raises an error that is propagated to
the Observer, thus interrupting the stream of data.
Now, let’s use what we’ve learned for a little quiz…
Let’s see how we can manipulate the elements emitted by
an Observable using another transforming function.
Putting it all together
QUIZ -Filtering only negative temperatures
The filter method of the Observable class takes a
Predicate as argument and produces a second
Observable that emits only the elements that pass the
test defined by that Predicate. Supposing that you have
been asked to develop a warning system that alerts the
user when there is risk of snow, how can you use this
operator to create an Observable that emits the
temperature in degrees Celsius registered in a town, only
when it is below zero?
Quiz time!
Answer:
It's enough to take the Observable returned by the
method in slide 18 and apply to it the filter operator with
a Predicate function that accepts only negative
temperature as it follows:
Quiz time!
That’s all for now!
Hopefully, you’ve learned a bit and had some fun doing it.
Don’t forget to save 42% off Modern Java in Action with
code slurma at manning.com.
Also see:

More Related Content

Similar to Modern Java in Action: learn all the things Java can do

RxJava 2 Reactive extensions for the JVM
RxJava 2  Reactive extensions for the JVMRxJava 2  Reactive extensions for the JVM
RxJava 2 Reactive extensions for the JVMNetesh Kumar
 
Reactive programming with rx java
Reactive programming with rx javaReactive programming with rx java
Reactive programming with rx javaCongTrung Vnit
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 SlidesYarikS
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaNexThoughts Technologies
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroidSavvycom Savvycom
 
Instrumentation and measurements
Instrumentation and measurementsInstrumentation and measurements
Instrumentation and measurementsTuba Tanveer
 
RxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android MontréalRxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android MontréalSidereo
 
Sperasoft Talks: RxJava Functional Reactive Programming on Android
Sperasoft Talks: RxJava Functional Reactive Programming on AndroidSperasoft Talks: RxJava Functional Reactive Programming on Android
Sperasoft Talks: RxJava Functional Reactive Programming on AndroidSperasoft
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with trackerDesignveloper
 
Combine Framework
Combine FrameworkCombine Framework
Combine FrameworkCleveroad
 
Guide to Spring Reactive Programming using WebFlux
Guide to Spring Reactive Programming using WebFluxGuide to Spring Reactive Programming using WebFlux
Guide to Spring Reactive Programming using WebFluxInexture Solutions
 
RxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMixRxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMixTracy Lee
 
How to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksHow to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksKaty Slemon
 
downloads_introduction to redux.pptx
downloads_introduction to redux.pptxdownloads_introduction to redux.pptx
downloads_introduction to redux.pptxNavneetKumar111924
 
Angular 16 – the rise of Signals
Angular 16 – the rise of SignalsAngular 16 – the rise of Signals
Angular 16 – the rise of SignalsCoding Academy
 

Similar to Modern Java in Action: learn all the things Java can do (20)

RxJava 2 Reactive extensions for the JVM
RxJava 2  Reactive extensions for the JVMRxJava 2  Reactive extensions for the JVM
RxJava 2 Reactive extensions for the JVM
 
Reactive programming with rx java
Reactive programming with rx javaReactive programming with rx java
Reactive programming with rx java
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJava
 
Intro to Rx Java
Intro to Rx JavaIntro to Rx Java
Intro to Rx Java
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
 
Rxandroid
RxandroidRxandroid
Rxandroid
 
RxAndroid
RxAndroidRxAndroid
RxAndroid
 
Instrumentation and measurements
Instrumentation and measurementsInstrumentation and measurements
Instrumentation and measurements
 
RxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android MontréalRxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android Montréal
 
Sperasoft Talks: RxJava Functional Reactive Programming on Android
Sperasoft Talks: RxJava Functional Reactive Programming on AndroidSperasoft Talks: RxJava Functional Reactive Programming on Android
Sperasoft Talks: RxJava Functional Reactive Programming on Android
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with tracker
 
Combine Framework
Combine FrameworkCombine Framework
Combine Framework
 
Guide to Spring Reactive Programming using WebFlux
Guide to Spring Reactive Programming using WebFluxGuide to Spring Reactive Programming using WebFlux
Guide to Spring Reactive Programming using WebFlux
 
RxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMixRxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMix
 
How to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksHow to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooks
 
downloads_introduction to redux.pptx
downloads_introduction to redux.pptxdownloads_introduction to redux.pptx
downloads_introduction to redux.pptx
 
Angular 16 – the rise of Signals
Angular 16 – the rise of SignalsAngular 16 – the rise of Signals
Angular 16 – the rise of Signals
 
RxJava@DAUG
RxJava@DAUGRxJava@DAUG
RxJava@DAUG
 

More from Manning Publications

Privacy-Preserving Machine Learning: secure user data without sacrificing mod...
Privacy-Preserving Machine Learning: secure user data without sacrificing mod...Privacy-Preserving Machine Learning: secure user data without sacrificing mod...
Privacy-Preserving Machine Learning: secure user data without sacrificing mod...Manning Publications
 
Inside Deep Learning: theory and practice of modern deep learning
Inside Deep Learning: theory and practice of modern deep learningInside Deep Learning: theory and practice of modern deep learning
Inside Deep Learning: theory and practice of modern deep learningManning Publications
 
Data-Oriented Programming: making data a first-class citizen
Data-Oriented Programming: making data a first-class citizenData-Oriented Programming: making data a first-class citizen
Data-Oriented Programming: making data a first-class citizenManning Publications
 
Automated Machine Learning in Action
Automated Machine Learning in ActionAutomated Machine Learning in Action
Automated Machine Learning in ActionManning Publications
 
The Programmer's Brain: improve the way you learn and think about code
The Programmer's Brain: improve the way you learn and think about codeThe Programmer's Brain: improve the way you learn and think about code
The Programmer's Brain: improve the way you learn and think about codeManning Publications
 
Pipeline as Code: building a great deployment pipeline
Pipeline as Code: building a great deployment pipelinePipeline as Code: building a great deployment pipeline
Pipeline as Code: building a great deployment pipelineManning Publications
 
Tuning Up: keep your systems running smoothly
Tuning Up: keep your systems running smoothlyTuning Up: keep your systems running smoothly
Tuning Up: keep your systems running smoothlyManning Publications
 
Kubernetes Native Microservices with Quarkus and MicroProfile
Kubernetes Native Microservices with Quarkus and MicroProfileKubernetes Native Microservices with Quarkus and MicroProfile
Kubernetes Native Microservices with Quarkus and MicroProfileManning Publications
 
Crafting interactive troubleshooting guides and team documentation for your K...
Crafting interactive troubleshooting guides and team documentation for your K...Crafting interactive troubleshooting guides and team documentation for your K...
Crafting interactive troubleshooting guides and team documentation for your K...Manning Publications
 
Entity Framework Core in Action, Second Edtion
Entity Framework Core in Action, Second EdtionEntity Framework Core in Action, Second Edtion
Entity Framework Core in Action, Second EdtionManning Publications
 
Microservices in .NET Core, Second Edition
Microservices in .NET Core, Second EditionMicroservices in .NET Core, Second Edition
Microservices in .NET Core, Second EditionManning Publications
 
Kubernetes in Action, Second Edition
Kubernetes in Action, Second EditionKubernetes in Action, Second Edition
Kubernetes in Action, Second EditionManning Publications
 
Machine Learning with TensorFlow, Second Edition
Machine Learning with TensorFlow, Second EditionMachine Learning with TensorFlow, Second Edition
Machine Learning with TensorFlow, Second EditionManning Publications
 
Spring Microservices in Action, Second Edition
Spring Microservices in Action, Second EditionSpring Microservices in Action, Second Edition
Spring Microservices in Action, Second EditionManning Publications
 

More from Manning Publications (20)

Privacy-Preserving Machine Learning: secure user data without sacrificing mod...
Privacy-Preserving Machine Learning: secure user data without sacrificing mod...Privacy-Preserving Machine Learning: secure user data without sacrificing mod...
Privacy-Preserving Machine Learning: secure user data without sacrificing mod...
 
Inside Deep Learning: theory and practice of modern deep learning
Inside Deep Learning: theory and practice of modern deep learningInside Deep Learning: theory and practice of modern deep learning
Inside Deep Learning: theory and practice of modern deep learning
 
Data-Oriented Programming: making data a first-class citizen
Data-Oriented Programming: making data a first-class citizenData-Oriented Programming: making data a first-class citizen
Data-Oriented Programming: making data a first-class citizen
 
Automated Machine Learning in Action
Automated Machine Learning in ActionAutomated Machine Learning in Action
Automated Machine Learning in Action
 
The Programmer's Brain: improve the way you learn and think about code
The Programmer's Brain: improve the way you learn and think about codeThe Programmer's Brain: improve the way you learn and think about code
The Programmer's Brain: improve the way you learn and think about code
 
Pipeline as Code: building a great deployment pipeline
Pipeline as Code: building a great deployment pipelinePipeline as Code: building a great deployment pipeline
Pipeline as Code: building a great deployment pipeline
 
Tuning Up: keep your systems running smoothly
Tuning Up: keep your systems running smoothlyTuning Up: keep your systems running smoothly
Tuning Up: keep your systems running smoothly
 
Kubernetes Native Microservices with Quarkus and MicroProfile
Kubernetes Native Microservices with Quarkus and MicroProfileKubernetes Native Microservices with Quarkus and MicroProfile
Kubernetes Native Microservices with Quarkus and MicroProfile
 
Cloud Native Machine Learning
Cloud Native Machine Learning Cloud Native Machine Learning
Cloud Native Machine Learning
 
Spring in Action, Sixth Edition
Spring in Action, Sixth EditionSpring in Action, Sixth Edition
Spring in Action, Sixth Edition
 
Crafting interactive troubleshooting guides and team documentation for your K...
Crafting interactive troubleshooting guides and team documentation for your K...Crafting interactive troubleshooting guides and team documentation for your K...
Crafting interactive troubleshooting guides and team documentation for your K...
 
Entity Framework Core in Action, Second Edtion
Entity Framework Core in Action, Second EdtionEntity Framework Core in Action, Second Edtion
Entity Framework Core in Action, Second Edtion
 
Code like a Pro in C#
Code like a Pro in C#Code like a Pro in C#
Code like a Pro in C#
 
Microservices in .NET Core, Second Edition
Microservices in .NET Core, Second EditionMicroservices in .NET Core, Second Edition
Microservices in .NET Core, Second Edition
 
Kubernetes in Action, Second Edition
Kubernetes in Action, Second EditionKubernetes in Action, Second Edition
Kubernetes in Action, Second Edition
 
Core Kubernetes
Core KubernetesCore Kubernetes
Core Kubernetes
 
Machine Learning Bookcamp
Machine Learning BookcampMachine Learning Bookcamp
Machine Learning Bookcamp
 
Machine Learning with TensorFlow, Second Edition
Machine Learning with TensorFlow, Second EditionMachine Learning with TensorFlow, Second Edition
Machine Learning with TensorFlow, Second Edition
 
Spring Security in Action
Spring Security in ActionSpring Security in Action
Spring Security in Action
 
Spring Microservices in Action, Second Edition
Spring Microservices in Action, Second EditionSpring Microservices in Action, Second Edition
Spring Microservices in Action, Second Edition
 

Recently uploaded

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 

Recently uploaded (20)

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 

Modern Java in Action: learn all the things Java can do

  • 1. Creating and using an Observable with RxJava. Save 42% off Modern Java in Action with code slurma at manning.com
  • 2. Both the Observable and Flowable classes come with tons of convenient factory methods to create many different types of reactive streams. The simplest Observable that you may want to create is one that is made of a fixed number of predetermined elements. An example of an observable that emits a fixed number of predetermined elements: Observables
  • 3. The just factory method converts one or more elements into an Observable that emits those elements. Another Observable that is quite common, especially when time is a relevant factor in your application, is one that emits events at a fixed time rate. An example of an Observable that emits a sequence of ascending longs, one per second: Observables
  • 4. The interval factory method returns in fact an Observable that emits an infinite sequence of ascending longs, with a constant interval of time of your choosing (one second In the former example) between emissions. We can try to use the Observable defined in the previous slide as the basis to create another Observable that emits the temperature detected in a given town each second. As an intermediate step to reach this goal, let's start with the simpler task of printing those temperatures each second. Observables
  • 5. To track our temperatures by the second, we need to subscribe to an Observable in order to be notified by it every time a second is passed and then fetch and print the temperature of the town of our interest. In RxJava, the Observable plays the role of the Publisher in the Flow API, so the Observer corresponds to the Flow's Subscriber interface. The Observer Interface
  • 6. With RxJava’s API it is possible to subscribe an Observable with an Observer that implements only the onSubscribe method with a consumer of the received event, leaving the others undefined. By leveraging this feature it is possible to subscribe to the Observable defined in the listing and print the temperatures in New York once a second. Here’s what it looks like: Subscribing to an Observable
  • 7. There is an issue with the statement on the previous slide - the Observable emits one event per second and then the subscriber fetches the temperature in New York every second and prints it. Indeed, if you put this statement in a main and try to execute it you will see … nothing. This is because the Observable publishing an event per second is executed in a thread of RxJava's computation thread pool, and the main thread then terminates immediately. Subscribing to an Observable
  • 8. We can prevent this immediate termination simply by putting a thread sleep after this statement from slide 6: Doing so might give us the following output: Troubleshooting our Observable
  • 9. Now, since our Observer only implements the happy path and doesn't have any sort of error management, this will eventually blow up in our user's face. So let’s raise the bar a bit by adding error management, and generalizing what we have: we don't want to immediately print the temperatures, but provide to our user a factory method that returns an Observable emitting those temperatures once a second for at most 5 times before completing. Improving our Observable
  • 10. We can do this by using another factory method, named create, that instances an Observable from a lambda taking another Observer as its argument and returning void. This will make our Observable function better – i.e. the way we want it to! On the next slide you can see our new Observable. Improving our Observable
  • 12. In the previous slide we created the returned an Observable from a function that consumes an Observer sending to it the desired events. Internally we are subscribing on an Observable publishing an infinite sequence of ascending longs, one per second, in order to have a timer that emits an event each second. At this point it is easy to implement a complete Observer that subscribes to the Observable returned by this method and printing the temperatures published by it. Refining our Observable
  • 13. Here’s our Observable printing out received temperatures: Our Observable in Action
  • 14. We are now ready to create a main where we subscribe this Observer to the Observable returned by the method of slide 10 in order to print the temperatures in New York. Creating a main
  • 15. It turned out to be necessary to add a sleep at the end of the main method because the Observable works in a thread of RxJava's pool and we need to give it time to perform its job. As long as there isn’t an error while fetching the temperatures, the main will print a line per second for 5 times and then the Observable will emit the complete signal, so we might get an output like the following: Creating a main
  • 16. Let’s take our RxJava example a bit further to show how this library allows manipulation of one or more reactive streams. One of the main advantages of RxJava and other reactive libraries, while working with reactive streams (compared with what is offered by the native Java Flow API), is that they provide a rich toolbox of functions to combine, create, and filter any of those streams. Manipulating reactive streams
  • 17. We’ve seen a stream getting used as an input to another one, but it is also possible to filter a stream to get another one that has only those elements you are interested in, transform those elements with a given mapping function, or even merge or combine two streams in many different ways. To overcome the problem of explaining function behavior in plain words –which often comes out rather cryptic– the reactive streams community documents functions using marble diagrams. Manipulating reactive streams
  • 19. Using this type of notation it's easy to provide a visual representation of the features of all of RxJava's functions, like map and merge (shown below) or a typical Observer like on the previous slide. A marble diagram
  • 20. So how can we put these two functions to use with our thermometer example? First, let’s put map to work converting from Fahrenheit to Celsius, previously implemented using the Flow API's Processor. This simple method takes the Observable returned by our getTemperature from slide 10 and converts the temperatures to Celsius. Putting it all together
  • 21. Now, let’s imagine that we need to emit temps for a group of towns, rather than one. We can perform the method from the previous slide for each town and combine the Observables together using the merge function. This method takes a varargs, containing the set of towns for which we are emitting temps, as an argument. Putting it all together
  • 22. The varargs gets put into a Stream of String, and then each String is passed to the method from slide 18. Basically, each town is transformed into an Observable emitting a temperature every second. In the end, the Stream of Observables is collected into a List and the List is passed to the merge static factory method provided by the Observable class itself. This method takes an Iterable of Observables and combines their output so they act like a single Observable. Pretty cool! Putting it all together
  • 23. Let's also try to put this last method at work by using it in one last main class. Putting it all together
  • 24. You might have noticed that this last main class is nearly identical to the one from slide 13, but this one is now subscribing to the Observable returned by the method in slide 19 and printing the temperatures registered in 3 different towns. When run, it should give an output like this: Putting it all together
  • 25. As you can see, each second it prints the temperatures of each of the requested towns until one of the temperature fetching operations raises an error that is propagated to the Observer, thus interrupting the stream of data. Now, let’s use what we’ve learned for a little quiz… Let’s see how we can manipulate the elements emitted by an Observable using another transforming function. Putting it all together
  • 26. QUIZ -Filtering only negative temperatures The filter method of the Observable class takes a Predicate as argument and produces a second Observable that emits only the elements that pass the test defined by that Predicate. Supposing that you have been asked to develop a warning system that alerts the user when there is risk of snow, how can you use this operator to create an Observable that emits the temperature in degrees Celsius registered in a town, only when it is below zero? Quiz time!
  • 27. Answer: It's enough to take the Observable returned by the method in slide 18 and apply to it the filter operator with a Predicate function that accepts only negative temperature as it follows: Quiz time!
  • 28. That’s all for now! Hopefully, you’ve learned a bit and had some fun doing it. Don’t forget to save 42% off Modern Java in Action with code slurma at manning.com. Also see: