RxJava Essentials 1st Edition Morgillo Ivan pdf download
RxJava Essentials 1st Edition Morgillo Ivan pdf download
download
https://textbookfull.com/product/rxjava-essentials-1st-edition-
morgillo-ivan/
https://textbookfull.com/product/learning-embedded-android-n-
programming-1st-edition-ivan-morgillo/
https://textbookfull.com/product/reactive-programming-with-
rxjava-creating-asynchronous-event-based-applications-1st-
edition-tomasz-nurkiewicz-ben-christensen/
https://textbookfull.com/product/reactive-programming-with-
kotlin-first-edition-learn-rx-with-rxjava-rxkotlin-and-rxandroid-
alex-sullivan/
https://textbookfull.com/product/style-in-theory-between-
literature-and-philosophy-1st-edition-ivan-callus/
Computation of Generalized Matrix Inverses and
Applications 1st Edition Ivan Stanimirovi■
https://textbookfull.com/product/computation-of-generalized-
matrix-inverses-and-applications-1st-edition-ivan-stanimirovic/
https://textbookfull.com/product/prolog-programming-for-
artificial-intelligence-ivan-bratko/
https://textbookfull.com/product/pipeline-steels-for-sour-
service-ivan-shabalov/
https://textbookfull.com/product/epistemic-democracy-and-
political-legitimacy-ivan-cerovac/
https://textbookfull.com/product/pathology-for-the-health-
professions-ivan-damjanov/
RxJava Essentials
Ivan Morgillo
BIRMINGHAM - MUMBAI
RxJava Essentials
All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
ISBN 978-1-78439-910-8
www.packtpub.com
Credits
Reviewer Proofreaders
David Moten Stephen Copestake
Safis Editing
Commissioning Editor
Ashwin Nair Indexer
Priya Sane
Acquisition Editor
Harsha Bharwani Production Coordinator
Shantanu N. Zagade
Content Development Editor
Prachi Bisht Cover Work
Shantanu N. Zagade
Technical Editor
Mrunal M. Chavan
Copy Editor
Stuti Srivastava
About the Author
Ivan Morgillo was just a kid with a C64 and some basic skills before becoming
an engineer a few years later. After working as an embedded systems consultant
for Italtel and Telecom Italia, he moved to Android. He worked as a consultant for
Deltatre, Mondia Media, and Clevertech.
David Moten has been programming in Java since 2001, largely with the
Australian government. He learned Scala in 2007, which made him strongly
appreciate the functional style, and he was delighted to discover RxJava when
he went looking for functional libraries for Java in early 2014. He loves a bit of
math when it turns up, and he is enjoying learning the tricks of the concurrent
programming trade by contributing to the RxJava project on GitHub.
www.PacktPub.com
Did you know that Packt offers eBook versions of every book published, with PDF
and ePub files available? You can upgrade to the eBook version at www.PacktPub.com
and as a print book customer, you are entitled to a discount on the eBook copy. Get in
touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign
up for a range of free newsletters and receive exclusive discounts and offers on Packt
books and eBooks.
TM
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser
[i]
Table of Contents
[ ii ]
Table of Contents
[ iii ]
Preface
In a world where there is a smartphone in every pocket, designing and building
applications that can run smoothly and provide a user experience that users will
enjoy is the only way to go. The reactive programming style with RxJava will help
you beat Android Platform limitations to create astonishing Android Apps.
This book will be a practical journey, from the basics of reactive programming and
Observer pattern concepts, to the main feature of RxJava, which will be accompanied
by practical code examples and a real-world app.
I'll show you how to create an Observable from "scratch", from a list, or from a
function that we already have in our codebase. You will learn how to filter an
Observable sequence to create a new sequence, containing only the values we want;
you will also learn how to apply a function to an Observable and how to concatenate,
merge, or zip Observables. I'll show you how to enjoy RxAndroid Schedulers to
overcome the threading and concurrency hell in Android.
The book will wind up with a practical example of RxJava combined with Retrofit to
easily communicate with a REST API.
Chapter 2, Why Observables?, gives an overview of the Observer pattern, how it's
implemented and extended by RxJava, what an Observable is, and how Observables
relate to Iterables.
Chapter 3, Hello Reactive World, uses what we have learned so far to create our first
reactive Android app.
[v]
Preface
Chapter 6, Combining Observables, digs into combining functions, and we are going
to learn how to work with multiple Observables simultaneously when we create the
Observable we want.
Chapter 7, Schedulers – Defeating the Android MainThread Issue, shows you how to
work with multithreading and concurrent programming using RxJava Schedulers.
We will create network operations, memory accesses, and time-consuming tasks
in a reactive way.
Chapter 8, REST in Peace – RxJava and Retrofit, teaches you how Retrofit by Square can
be used with RxJava to create an REST client efficiently and effectively.
As you are approaching RxJava as a pure Java developer, you will obviously
need your preferred Java editor and a standard Java JDK environment. Some
of the figures used in this book are taken from http://rxmarbles.com/ and
http://reactivex.io/.
[ vi ]
Preface
Conventions
In this book, you will find a number of text styles that distinguish between different
kinds of information. Here are some examples of these styles and an explanation of
their meaning.
Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"As you can see, zip() has three parameters: the two Observables and Func2,
as expected."
New terms and important words are shown in bold. Words that you see on
the screen, for example, in menus or dialog boxes, appear in the text like this:
"We will just need a fancy progress bar and a DOWNLOAD button."
[ vii ]
Preface
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or disliked. Reader feedback is important for us as it helps
us develop titles that you will really get the most out of.
If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you could report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you find any errata, please report them by visiting http://www.packtpub.
com/submit-errata, selecting your book, clicking on the Errata Submission Form
link, and entering the details of your errata. Once your errata are verified, your
submission will be accepted and the errata will be uploaded to our website or
added to any list of existing errata under the Errata section of that title.
[ viii ]
Preface
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all
media. At Packt, we take the protection of our copyright and licenses very seriously.
If you come across any illegal copies of our works in any form on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.
We appreciate your help in protecting our authors and our ability to bring you
valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at
[email protected], and we will do our best to address the problem.
[ ix ]
RX – from .NET to RxJava
Reactive programming is a programming paradigm based on the concept of an
asynchronous data flow. A data flow is like a river: it can be observed, filtered,
manipulated, or merged with a second flow to create a new flow for a new consumer.
A key concept of reactive programming is events. Events can be awaited, can trigger
procedures, and can trigger other events. Events are the only proper way to map our
real world to our software: we open a window if it's too hot inside. In the same way,
we want the Total cell to update when we change some values in our spreadsheet
(the propagation of the changes) or our robot to turn around the moment it reaches
the wall (reaction to events).
Nowadays, one of the most common scenarios for reactive programming is UIs:
we have mobile apps that have to react to network calls, user touch input, and
system alerts. In this world, software has to be event-driven and reactive because
real life is event-driven.
[1]
RX – from .NET to RxJava
The push approach reverses the problem: instead of asking for a result and waiting,
the developer simply asks for a result and gets notified when the result is available.
The developer provides a clear sequence of reactions to the events that are going to
happen. For every event, the developer provides a reaction; for example, the user is
asked to log in and submit a form with his username and password. The application
executes the network call for the login and states what is going to happen:
As you can see with the push approach, the developer doesn't wait for the result.
He will be notified when the result arrives. In the meantime, he can do whatever
he wants:
[2]
Chapter 1
To achieve this goal, they decided to go reactive, and they started to port .NET Rx to
the JVM. They didn't want to target just Java; they decided to target the JVM instead,
having the possibility to provide a new tool for every JVM language on the market:
Java, Closure, Groovy, Scala, and so on.
With a post on the Netflix tech blog in February 2013, Ben Christensen and Jafar
Husain showed RxJava to the world for the first time.
As for .NET, RxJava Observable is the push equivalent of Iterable, which is pull.
The pull approach is a block-and-wait approach: the consumer pulls values from
the source, blocking the thread until the producer provides new values.
The push approach works on subscription and reaction: the consumer subscribes
to new values' emissions; the producer pushes these new values when they are
available, and notifies the consumer. At this point, the consumer, well, consumes
them. The push approach is clearly more flexible, because from a logical and
practical point of view, the developer can simply ignore if the data he needs
comes synchronously or asynchronously; his code will still work.
• The producer can now signal that there is no more data available: the
onCompleted() event
• The producer can now signal that an error occurred: the onError() event
• RxJava Observables can be composed instead of nested, saving the developer
from the callback hell
[3]
RX – from .NET to RxJava
Observables and Iterables share a similar API; lots of operations that we can perform
on Iterable can be performed on Observable too. Of course, due to the "flow" nature
of Observables, we don't have equivalents for methods such as Iterable.remove().
From a semantic point of view, RxJava is .NET Rx. From a syntactical point of
view, Netflix takes care of porting every Rx method, keeping in mind Java code
conventions and basic patterns.
Summary
In this chapter, we took the initial steps into the reactive world. We learned how Rx
was born, from Microsoft .NET to Netflix RxJava. We learned the similarities and
differences of the reactive approach compared with the classic approach.
In the next chapter, we will learn what Observables are, and how we can create
them to bring reactive programming into our daily coding life.
[4]
Why Observables?
In object-oriented architectures, the developer works hard to create a set of
decoupled entities. In this way, entities can be tested, reused, and maintained
without interfering with the whole system. Designing this kind of system brings
a tricky side effect: maintaining consistency between related objects.
The first example of a pattern created to solve this issue was in the Smalltalk
Model-View-Controller architecture. The user interface framework provided a
way to keep UI elements separated from the actual object containing the data,
and, at the same time, it provided a handy way to keep everything in sync.
The Observer pattern is one of the most famous design patterns discussed in the
popular Design Patterns: Elements of Reusable Object-Oriented Software by The Gang of
Four. It's a behavioral pattern and it provides a way to bind objects in a one-to-many
dependency: when one object changes, all the objects depending on it are notified
and updated automatically.
[5]
Why Observables?
In the previous chapter, we saw the spreadsheet example. Now we can expand
the example, showing a more complex scenario. Let's think about a spreadsheet
containing the accounting data. We could represent this data as a table, as a
3D-histogram, or as a pie chart. Every one of these representations will depend on
the same set of data being displayed. Every one of these representations will be an
Observer, depending on one single subject, maintaining all the information.
The 3D-histogram class, the pie chart class, the table class, and the class maintaining
the data are perfectly decoupled: they can be used and reused independently, but
they can work together too. The representation classes don't know each other, but
they act like they do: they know where to find the information they need to show,
and they know that they have to update their data representation the moment the
data changes are notified.
The previous figure shows that one single subject can serve three Observers.
Obviously, there is no reason to limit the number of Observers: a subject could have
an infinite number of Observers if necessary, and every one of them will be notified
when the subject state changes.
[6]
Chapter 2
• When your architecture has two entities, one depending on the other,
and you want to keep them separated to change them or reuse them
independently
• When a changing object has to notify an unknown amount of related
objects about its own change
• When a changing object has to notify other objects without making
assumptions about who these objects are
• Observable
• Observer
• Subscriber
• Subjects
Observables and Subjects are the two "producing" entities. Observers and
Subscribers are the two "consuming" entities.
Observable
When we have to execute something asynchronously with a lite level of
complexity, Java provides classic classes, such as Thread, Future, FutureTask,
CompletableFuture, to approach the problem. When the level of complexity goes
up, these solutions tend to become messy and hard to maintain. Most of all, they
cannot be chained.
RxJava Observables were designed to solve these issues. They are flexible and easy
to use, they can be chained, and they can work on a single result routine or, even
better, on sequences. Whenever you want to emit a single scalar value or a sequence
of values, or even an infinite value stream, you can use an Observable.
[7]
Why Observables?
The Observable life cycle contains three possible events that we can easily compare
to Iterable life cycle events. The next table shows how the Observable async/push
approach relates to the Iterable sync/pull one:
With Iterable, the consumer synchronously pulls values from the producer and
the thread is blocked until these values arrive. By contrast, with Observable, the
producer asynchronously pushes values to the Observer whenever values are available.
This approach is more flexible because even if values arrive synchronously or
asynchronously, the consumer can act according to expectations in both scenarios.
To properly replicate the same Iterable interface, the RxJava Observable class
enhances the base semantic of the Observer pattern by the Gang of Four, and
introduces two new abilities:
• onCompleted(), that is, the ability to notify the Observer that there is no
more data coming from the Observable
• onError(), that is, the ability to notify the Observer that an error occurred
Keeping in mind these two abilities and the preceding table, we know that
Observables and Iterables have a comparable abilities set but a different data
flow direction: push versus pull.
Creating an Observable
The Observable class provides the ways discussed in the upcoming sections to create
an Observable.
[8]
Chapter 2
Observable.create()
The create() method gives the developer the ability to create an Observable from
scratch. It takes an OnSubscribe object, which extends Action1, as a parameter and
executes the call() function when an Observer subscribes to our Observable:
Observable
.create(new Observable.OnSubscribe<Object>() {
@Override
public void call(Subscriber<? super Object> subscriber) {
}
});
Observable communicates with the Observer using the subscriber variable and
by calling its methods according to the conditions. Let's see a real-world example:
Observable<Integer> observableString =
Observable.create(new Observable.OnSubscribe<Integer>() {
@Override
public void call(Subscriber<? super Integer> observer) {
observer.onCompleted();
}
});
Subscription subscriptionPrint =
observableString.subscribe(new Observer<Integer>() {
@Override
public void onCompleted() {
System.out.println("Observable completed");
}
[9]
Why Observables?
@Override
public void onError(Throwable e) {
System.out.println("Oh no! Something wrong happened!");
}
@Override
public void onNext(Integer item) {
System.out.println("Item is " + item);
}
});
The example is kept simple on purpose, because even if it's the first time you see
RxJava in action, I want you to be able to figure out what's going on.
Observable.from()
In the previous example, we created a sequence of integers and emitted them one by
one. What if we already have a list? Can we save the for loop but still emit items one
by one?
Observable<Integer> observableString =
Observable.from(items);
Subscription subscriptionPrint =
observableString.subscribe(new Observer<Integer>() {
@Override
[ 10 ]
Chapter 2
@Override
public void onNext(Integer item) {
System.out.println("Item is " + item);
}
});
The from() creator can create an Observable from a list/array, emitting every object
contained in the list/array one by one or from a Java Future class, emitting the result
value of the .get() method of the Future object. Passing Future as parameter, we
can even specify a timeout value. The Observable will wait for a result from Future;
if no result comes before the timeout, the Observable will fire the onError() method
and notify the Observer that something was wrong.
Observable.just()
What if we already have a classic Java function and we want to transform it in an
Observable? We could use the create() method, as we already saw, or we can
avoid a lot of boilerplate code using something like this:
Observable<String> observableString =
Observable.just(helloWorld());
Subscription subscriptionPrint =
observableString.subscribe(new Observer<String>() {
@Override
public void onCompleted() {
System.out.println("Observable completed");
}
@Override
public void onError(Throwable e) {
System.out.println("Oh no! Something wrong happened!");
}
@Override
public void onNext(String message) {
System.out.println(message);
}
});
[ 11 ]
Why Observables?
However, this could be any function we want. In the previous example, the moment
we create the Observable, just() executes the function and when we subscribe to
our Observable, it emits the returned value.
The just() creator can take between one and nine parameters. It will emit them in
the same order as they are given as parameters. The just() creator also accepts lists
or arrays, like from(), but it won't iterate on the list, emitting every value, it will just
emit the whole list. Usually, it's used when we want to emit a defined set of values,
but if our function is not time-variant, we can use just() to have a more organized
and testable code base.
As a final note about the just() creator, after emitting the value, the Observable
terminates normally. For the previous example, we will have two messages on the
system console: "Hello World" and "Observable completed".
The moment the subject subscribes to the Observable, it will trigger the Observable
to begin emitting. If the original Observable is cold, this can have the effect of making
the resulting subject a hot Observable variant of the original cold Observable.
[ 12 ]
Random documents with unrelated
content Scribd suggests to you:
small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.
Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com