The release of Java 9 builds on what made Java 8 so exciting. In addition to Java 8's lambdas and streams, Java 9 adds a host of new features of its own.
Manning's bestselling Java 8 book has been revised for Java 9! In Java 8 and 9 in Action, you'll build on your existing Java language skills with the newest features and techniques.
Save 42% off Modern Java in Action with code slurma at: https://goo.gl/b7a1Za
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
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: