Java Reference
In-Depth Information
of declarative programming that lets us program in terms of changes and data flows that get
automatically propagated.
You can think of a spreadsheet as a commonly used example of reactive programming. If you
enter
=B1+5
in cell
C1
, it tells the spreadsheet to add
5
to the contents of cell
B1
and put the
result in
C1
. In addition, the spreadsheet reacts to any future changes in
B1
and updates the
value in
C1
.
The RxJava library is a port of these reactive ideas onto the JVM. We won't be going into the
library in huge amounts of depth here, just covering the key concepts.
RxJava introduces a class called
Observable
that represents a sequence of events that you
can react to. It's an IOU for a sequence. There is a strong connection between an
Observ-
In both cases we build up recipes for performing work by chaining higher-order functions
and use lambda expressions in order to associate behavior with these general operations. In
fact, many of the operations defined on an
Observable
are the same as on a
Stream
:
map
,
filter
,
reduce
.
The big difference between the approaches is the use case. Streams are designed to build up
computational workflows over in-memory collections. RxJava, on the other hand, is de-
signed to compose and sequence asynchronous and event-based systems. Instead of pulling
data out, it gets pushed in. Another way of thinking about RxJava is that it is to a sequence of
values what a
CompletableFuture
is to a single value.
Our concrete example this time around is searching for an artist and is shown in
al cache of artist names but must look up other artist information, such as nationality, from
external services.
Example 9-15. Searching for an artist by name and nationality
public
public
Observable
<
Artist
>
search
(
String searchedName
,
String searchedNationality
,
int
int
maxResults
) {
return
return
getSavedArtists
()
.
filter
(
name
->
name
.
contains
(
searchedName
))
.
flatMap
(
this
this
::
lookupArtist
)
.
filter
(
artist
->
artist
.
getNationality
()
.
contains
(
searchedNationality
))