100% found this document useful (3 votes)
21 views

RxJava Essentials 1st Edition Morgillo Ivan pdf download

RxJava Essentials by Ivan Morgillo is a practical guide to learning reactive programming for Android and Java applications. The book covers the fundamentals of RxJava, including Observables, filtering, transforming, and combining data streams, as well as handling multithreading issues in Android. It concludes with a real-world example of integrating RxJava with Retrofit for REST API communication.

Uploaded by

batorjukanils
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
21 views

RxJava Essentials 1st Edition Morgillo Ivan pdf download

RxJava Essentials by Ivan Morgillo is a practical guide to learning reactive programming for Android and Java applications. The book covers the fundamentals of RxJava, including Observables, filtering, transforming, and combining data streams, as well as handling multithreading issues in Android. It concludes with a real-world example of integrating RxJava with Retrofit for REST API communication.

Uploaded by

batorjukanils
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

RxJava Essentials 1st Edition Morgillo Ivan

download

https://textbookfull.com/product/rxjava-essentials-1st-edition-
morgillo-ivan/

Download more ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

Learning embedded Android N programming 1st Edition


Ivan Morgillo

https://textbookfull.com/product/learning-embedded-android-n-
programming-1st-edition-ivan-morgillo/

Reactive Programming with RxJava Creating Asynchronous


Event Based Applications 1st Edition Tomasz Nurkiewicz
Ben Christensen

https://textbookfull.com/product/reactive-programming-with-
rxjava-creating-asynchronous-event-based-applications-1st-
edition-tomasz-nurkiewicz-ben-christensen/

Reactive Programming with Kotlin First Edition Learn Rx


with RxJava RxKotlin and RXAndroid Alex Sullivan

https://textbookfull.com/product/reactive-programming-with-
kotlin-first-edition-learn-rx-with-rxjava-rxkotlin-and-rxandroid-
alex-sullivan/

Style in Theory Between Literature and Philosophy 1st


Edition Ivan Callus

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/

Prolog programming for artificial intelligence Ivan


Bratko

https://textbookfull.com/product/prolog-programming-for-
artificial-intelligence-ivan-bratko/

Pipeline Steels for Sour Service Ivan Shabalov

https://textbookfull.com/product/pipeline-steels-for-sour-
service-ivan-shabalov/

Epistemic Democracy and Political Legitimacy Ivan


Cerovac

https://textbookfull.com/product/epistemic-democracy-and-
political-legitimacy-ivan-cerovac/

Pathology for the Health Professions Ivan Damjanov

https://textbookfull.com/product/pathology-for-the-health-
professions-ivan-damjanov/
RxJava Essentials

Learn reactive programming to create awesome


Android and Java apps

Ivan Morgillo

BIRMINGHAM - MUMBAI
RxJava Essentials

Copyright © 2015 Packt Publishing

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.

First published: May 2015

Production reference: 1220515

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-78439-910-8

www.packtpub.com
Credits

Author Project Coordinator


Ivan Morgillo Sanjeet Rao

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.

He currently runs a mobile and embedded applications development company,


Alter Ego Solutions, contributing to open source projects and still working on his
Android projects over the weekend.

I want to thank Francesca, my beloved, for her constant support and


infinite love; Sasa Sekulic, my company cofounder, for his perpetual
trolling; and Fabrizio Chignoli, who changed my life, teaching me
what reactive programming really is. This book is dedicated to my
family and my friends. I couldn't have been where I am without
their love.
About the Reviewer

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

Support files, eBooks, discount offers, and more


For support files and downloads related to your book, please visit 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

Free access for Packt account holders


If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view 9 entirely free books. Simply use your login credentials for
immediate access.
Table of Contents
Preface v
Chapter 1: RX – from .NET to RxJava 1
Microsoft Reactive Extensions 1
Landing in the Java world – Netflix RxJava 2
What's different in RxJava 3
Summary 4
Chapter 2: Why Observables? 5
The Observer pattern 5
When do you use the Observer pattern? 7
The RxJava Observer pattern toolkit 7
Observable 7
Hot and cold Observables 8
Creating an Observable 8
Subject = Observable + Observer 12
PublishSubject 13
BehaviorSubject 15
ReplaySubject 15
AsyncSubject 15
Summary 16
Chapter 3: Hello Reactive World 17
Start the engine! 17
Dependencies 19
RxAndroid 20
Utils 20
Lombok 20
Butter Knife 20
Retrolambda 20
Our first Observable 20
Creating an Observable from a list 25

[i]
Table of Contents

A few more examples 26


just() 26
repeat() 27
defer() 28
range() 29
interval() 30
timer() 30
Summary 31
Chapter 4: Filtering Observables 33
Filtering a sequence 33
Let's take what we need 36
Take 36
TakeLast 37
Once and only once 38
Distinct 38
DistinctUntilChanged 41
First and last 42
Skip and SkipLast 43
ElementAt 44
Sampling 44
Timeout 45
Debounce 47
Summary 47
Chapter 5: Transforming Observables 49
The *map family 49
Map 49
FlatMap 51
ConcatMap 51
FlatMapIterable 52
SwitchMap 52
Scan 53
GroupBy 56
Buffer 58
Window 60
Cast 61
Summary 61

[ ii ]
Table of Contents

Chapter 6: Combining Observables 63


Merge 63
Zip 66
Join 69
combineLatest 72
And, Then, and When 74
Switch 76
StartWith 77
Summary 78
Chapter 7: Schedulers – Defeating the Android MainThread Issue 79
StrictMode 79
Avoiding blocking I/O operations 80
Schedulers 81
Schedulers.io() 81
Schedulers.computation() 82
Schedulers.immediate() 82
Schedulers.newThread() 82
Schedulers.trampoline() 82
Nonblocking I/O operations 82
SubscribeOn and ObserveOn 84
Handling a long task 87
Executing a network task 90
Summary 96
Chapter 8: REST in Peace – RxJava and Retrofit 97
The project goal 97
Retrofit 97
The app structure 99
Creating the Activity class 99
Creating the RecyclerView adapter 100
Retrieving the weather forecast 102
Opening the website 106
Summary 107
Index 109

[ 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.

What this book covers


Chapter 1, RX – from .NET to RxJava, takes initial steps into the reactive world. We
will compare the reactive approach with the classic approach, and will explore the
similarities and differences between them.

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 4, Filtering Observables, dives into the essence of an Observable sequence:


filtering. We will also learn how to select only the values we want from an emitting
Observable, how to obtain a finite number of values, how to handle overflow
scenarios, and a few more useful tricks.

Chapter 5, Transforming Observables, shows how to transform Observable sequences to


create sequences that can fit our needs.

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.

What you need for this book


To run the examples in this book, you will need a standard Android
development environment:

• Android Studio or IntelliJ IDEA


• The Android SDK
• The Java JDK

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/.

Who this book is for


If you are an experienced Java developer, reactive programming will give you
a new way to approach scalability and concurrency in your backend systems,
without forcing you to switch to change the programming languages. This book
will help you learn the core aspects of RxJava and will also help you overcome the
limitations of the Android platform to create event-driven, reactive, and smooth
Android applications.

[ 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."

A block of code is set as follows:


public Observable<List<User>> getMostPopularSOusers(int howmany) {
return mStackExchangeService
.getMostPopularSOusers(howmany)
.map(UsersResponse::getUsers)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}

When we wish to draw your attention to a particular part of a code block,


the relevant lines or items are set in bold:
public Observable<List<User>> getMostPopularSOusers(int howmany) {
return mStackExchangeService
.getMostPopularSOusers(howmany)
.map(UsersResponse::getUsers)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}

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."

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

[ 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.

To send us general feedback, simply e-mail [email protected], and mention


the book's title in the subject of your message.

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.

Downloading the example code


You can download the example code files from your account at http://www.
packtpub.com for all the Packt Publishing books you have purchased. If you
purchased this book elsewhere, you can visit http://www.packtpub.com/support
and register to have the files e-mailed directly to you.

Downloading the color images of this book


We also provide you with a PDF file that has color images of the screenshots/
diagrams used in this book. The color images will help you better understand the
changes in the output. You can download this file from https://www.packtpub.
com/sites/default/files/downloads/9108OS_GraphicsBundle.pdf.

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

To view the previously submitted errata, go to https://www.packtpub.com/books/


content/support and enter the name of the book in the search field. The required
information will appear under the Errata section.

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.

Please contact us at [email protected] with a link to the suspected


pirated material.

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.

Microsoft Reactive Extensions


Functional reactive programming is an idea from the late 90s that inspired
Erik Meijer, a computer scientist at Microsoft, to design and develop the
Microsoft Rx library.

Rx is a reactive extension for Microsoft .NET. Rx provides an easy way to create


asynchronous, event-driven programs using Observable sequences. A developer can
model an asynchronous data stream using Observables, query the Observables using
LINQ syntax, and easily manage concurrency with Schedulers.

[1]
RX – from .NET to RxJava

Rx makes well-known concepts, such as the push approach, easy to implement


and consume. In a reactive world, we can't just wait for a function result, a network
call, or a database query to return and pretend that the user won't notice or even
complain about it. Every moment we wait for something, we lose the opportunity to
do other things in parallel, provide a better user experience, and free our software
from the chains of sequential, blocking programming.

.NET Observable relates to .NET Enumerable according to the following table:

.NET Observable Single return value Multiple return values


Pull/Synchronous/Interactive T IEnumerable<T>
Push/Asynchronous/Reactive Task<T> IObservable<T>

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:

• Show a success message and store the user's profile


• Show an error message

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:

• Show a progress dialog


• Store the username and password for future logins
• Preload something he knows would take some time the moment the
login succeeds

Landing in the Java world – Netflix


RxJava
In 2012, at Netflix, they started to realize that their architecture was having a hard
time to properly adapt to the amount of users they had. They decided to redesign
their architecture to reduce the number of REST calls. Instead of having dozens of
REST calls and letting the client process the data as needed, they decided to create a
single optimized REST call based on the clients' needs.

[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.

The key concepts were:

• Easy concurrency to better use their server's power


• Easy conditional asynchronous execution
• A proper way to escape the callback hell
• A reactive approach

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.

What's different in RxJava


From a pure Java point of view, the RxJava Observable class extends the classic
Gang of Four Observer pattern concept.

It adds three missing abilities:

• 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().

Pattern Single return value Multiple return values


Synchronous T getData() Iterable<T> getData()
Asynchronous Future<T> getData() Observable<T> getData()

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.

In this chapter, we are going to have an overview of the Observer pattern,


how it's implemented and extended by RxJava, what an Observable is, and how
Observables relate to Iterables.

The Observer pattern


Nowadays, the Observer pattern is one of the most common software design
patterns on the scene. It's based on the concept of subject. A subject is a particular
object that keeps a list of objects that want to be notified when the subject changes.
These objects are called Observers and they expose a notification method that the
subject invokes when its state changes.

[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 figure here depicts how the Subject/Observer relationship is a one-to-many


relationship:

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 do you use the Observer pattern?


The Observer pattern is the perfect fit for any of these scenarios:

• 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

The RxJava Observer pattern toolkit


In the RxJava world, we have four main players:

• 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:

Event Iterable (pull) Observable (push)


Retrieve the data T next() onNext(T)
Discover the error throws Exception onError(Throwable)
Complete !hasNext() onCompleted()

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.

Hot and cold Observables


From an emission point of view, there are two different types of Observables: hot and
cold. A hot Observable, typically, starts emitting items as soon as it is created, so
any Observer who subscribes to this Observable may start observing the sequence
somewhere in the middle. A cold Observable waits until an Observer subscribes to
it before it begins to emit items, so such an Observer is guaranteed to see the whole
sequence from the beginning.

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) {

}
});

Downloading the example code


You can download the example code files from your account at
http://www.packtpub.com for all the Packt Publishing books
you have purchased. If you purchased this book elsewhere, you can
visit http://www.packtpub.com/support and register to have
the files e-mailed directly to you.

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) {

for (int i = 0; i < 5; i++) {


observer.onNext(i);
}

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.

We created a new Observable<Integer> item that executes a for loop on five


elements, emitting them one by one, and then it completes.

On the other side, we subscribe to the Observable, obtaining a Subscription object.


The moment we subscribe, we start to receive integers and we print them one by one.
We don't know how many integers we will receive. Indeed, we don't need to know
because we provided behaviors for every possible scenario:

• If we receive an integer, we print it


• If the sequence ends, we print a closed sequence message
• If an error occurs, we print an error message

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?

In the following code example, we create an Observable sequence from a list we


already had:
List<Integer> items = new ArrayList<Integer>();
items.add(1);
items.add(10);
items.add(100);
items.add(200);

Observable<Integer> observableString =
Observable.from(items);
Subscription subscriptionPrint =
observableString.subscribe(new Observer<Integer>() {
@Override

[ 10 ]
Chapter 2

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(Integer item) {
System.out.println("Item is " + item);
}
});

The output is absolutely the same as that in the previous example.

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?

The helloworld() function is super easy, like this:


private String helloWorld() {
return "Hello World";
}

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".

Observable.empty(), Observable.never(), and


Observable.throw()
If for any reason we need an Observable emitting nothing but terminating normally,
we can use empty(). We can use never() to create an Observable emitting nothing
and never terminating, and we can use throw() to create an Observable emitting
nothing and terminating with an error.

Subject = Observable + Observer


A subject is a magic object that can be an Observable and an Observer at the same
time: it acts as a bridge connecting the two worlds. A subject can subscribe to an
Observable, acting like an Observer, and it can emit new items or even pass through
the item it received, acting like an Observable. Obviously, being an Observable,
Observers or other subjects can subscribe to it.

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.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

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.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like