0% found this document useful (0 votes)
7 views

Reactive Programming with RxJS Untangle Your Asynchronous JavaScript Code 1st Edition Sergi Mansilla download

The document provides information about the book 'Reactive Programming with RxJS' by Sergi Mansilla, which focuses on managing asynchronous JavaScript code using reactive programming techniques. It discusses the challenges of real-time web applications and how RxJS can help address these issues through the use of Observables. The book includes practical examples and aims to provide a clear roadmap for developers looking to improve their asynchronous programming skills.

Uploaded by

sadoevkupiec
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Reactive Programming with RxJS Untangle Your Asynchronous JavaScript Code 1st Edition Sergi Mansilla download

The document provides information about the book 'Reactive Programming with RxJS' by Sergi Mansilla, which focuses on managing asynchronous JavaScript code using reactive programming techniques. It discusses the challenges of real-time web applications and how RxJS can help address these issues through the use of Observables. The book includes practical examples and aims to provide a clear roadmap for developers looking to improve their asynchronous programming skills.

Uploaded by

sadoevkupiec
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Reactive Programming with RxJS Untangle Your

Asynchronous JavaScript Code 1st Edition Sergi


Mansilla pdf download

https://ebookfinal.com/download/reactive-programming-with-rxjs-
untangle-your-asynchronous-javascript-code-1st-edition-sergi-
mansilla/

Explore and download more ebooks or textbooks


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

HTML5 programming with JavaScript for dummies Mueller

https://ebookfinal.com/download/html5-programming-with-javascript-for-
dummies-mueller/

Asynchronous Android Programming 2nd Edition Helder


Vasconcelos

https://ebookfinal.com/download/asynchronous-android-programming-2nd-
edition-helder-vasconcelos/

Node Up and Running Scalable Server Side Code with


JavaScript 1st Edition Tom Hughes-Croucher

https://ebookfinal.com/download/node-up-and-running-scalable-server-
side-code-with-javascript-1st-edition-tom-hughes-croucher/

Programming Reactive Extensions and LINQ 1st Edition Jesse


Liberty

https://ebookfinal.com/download/programming-reactive-extensions-and-
linq-1st-edition-jesse-liberty/
Learn Unity3D Programming with UnityScript Unity s
JavaScript for Beginners 1st Edition Janine Suvak

https://ebookfinal.com/download/learn-unity3d-programming-with-
unityscript-unity-s-javascript-for-beginners-1st-edition-janine-suvak/

Modern C programming with test driven development code


better sleep better 1st Edition Jeff Langr

https://ebookfinal.com/download/modern-c-programming-with-test-driven-
development-code-better-sleep-better-1st-edition-jeff-langr/

Handbook of Asynchronous Machines with Variable Speed 1st


Edition Hubert Razik

https://ebookfinal.com/download/handbook-of-asynchronous-machines-
with-variable-speed-1st-edition-hubert-razik/

Learn Game Programming with Ruby Bring Your Ideas to Life


with Gosu Mark Sobkowicz

https://ebookfinal.com/download/learn-game-programming-with-ruby-
bring-your-ideas-to-life-with-gosu-mark-sobkowicz/

Getting Started With Advanced C Upgrade Your Programming


Skills 1st Edition Vaskaran Sarcar

https://ebookfinal.com/download/getting-started-with-advanced-c-
upgrade-your-programming-skills-1st-edition-vaskaran-sarcar/
Reactive Programming with RxJS Untangle Your
Asynchronous JavaScript Code 1st Edition Sergi Mansilla
Digital Instant Download
Author(s): Sergi Mansilla
ISBN(s): 9781680501292, 1680501291
Edition: 1
File Details: PDF, 3.65 MB
Year: 2015
Language: english
Early praise for Reactive Programming with RxJS

Every significant shift in software development demands rethinking our approach-


es. Real-time and asynchronous web applications pose a huge challenge in web
development today. This book does an excellent job explaining how RxJS addresses
those challenges and teaches you how to rethink your world in terms of Observ-
ables.
➤ Zef Hemel
VP engineering, STX Next

This book is as hot as reactive programming itself! With great writing, clear expla-
nations, and practical examples, this is a fantastic resource for learning RxJS.
➤ Fred Daoud
Software-development contractor

Be proactive and learn reactive programming with this book before it’s too late.
Rx.Observable.fromBook(book).subscribe(function(value) {...do amazing stuff...});
➤ Javier Collado Cabeza
Senior software developer, NowSecure, Inc.

A very readable book with great content. This book is eminently useful and provides
a clear roadmap for learning reactive programming with RxJS with practical ex-
amples.
➤ Ramaninder Singh Jhajj
Software engineer, Area Services & Development, Know-Center, Austria
We've left this page blank to
make the page numbers the
same in the electronic and
paper books.

We tried just leaving it out,


but then people wrote us to
ask about the missing pages.

Anyway, Eddy the Gerbil


wanted to say “hello.”
Reactive Programming with RxJS
Untangle Your Asynchronous JavaScript Code

Sergi Mansilla

The Pragmatic Bookshelf


Dallas, Texas • Raleigh, North Carolina
Many of the designations used by manufacturers and sellers to distinguish their products
are claimed as trademarks. Where those designations appear in this book, and The Pragmatic
Programmers, LLC was aware of a trademark claim, the designations have been printed in
initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer,
Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade-
marks of The Pragmatic Programmers, LLC.
Every precaution was taken in the preparation of this book. However, the publisher assumes
no responsibility for errors or omissions, or for damages that may result from the use of
information (including program listings) contained herein.
Our Pragmatic courses, workshops, and other products can help you and your team create
better software and have more fun. For more information, as well as the latest Pragmatic
titles, please visit us at https://pragprog.com.

The team that produced this book includes:


Rebecca Gulick (editor)
Potomac Indexing, LLC (index)
Candace Cunningham (copyedit)
Dave Thomas (layout)
Janet Furlow (producer)
Ellie Callahan (support)

For international rights, please contact rights@pragprog.com.

Copyright © 2015 The Pragmatic Programmers, LLC.


All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted,


in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise,
without the prior consent of the publisher.

Printed in the United States of America.


ISBN-13: 978-1-68050-129-2
Encoded using the finest acid-free high-entropy binary digits.
Book version: P1.0—December 2015
Per a tu, Pipus
Contents

Acknowledgments . . . . . . . . . . . ix
Preface . . . . . . . . . . . . . . xi

1. The Reactive Way . . . . . . . . . . . . 1


What’s Reactive? 1
Of Observers and Iterators 6
The Rx Pattern and the Observable 9
Creating Observables 10
Wrapping Up 15

2. Deep in the Sequence . . . . . . . . . . 17


Visualizing Observables 17
Basic Sequence Operators 19
Canceling Sequences 24
Handling Errors 26
Making a Real-Time Earthquake Visualizer 29
Ideas for Improvements 36
Operator Rundown 36
Wrapping Up 38

3. Building Concurrent Programs . . . . . . . . 39


Purity and the Observable Pipeline 39
RxJS’s Subject Class 45
Spaceship Reactive! 50
Ideas for Improvements 68
Wrapping Up 68

4. Building a Complete Web Application . . . . . . 69


Building a Real-Time Earthquake Dashboard 69
Adding a List of Earthquakes 71
Getting Real-Time Updates from Twitter 82
Contents • viii

Ideas for Improvements 88


Wrapping Up 88

5. Bending Time with Schedulers . . . . . . . . 89


Using Schedulers 89
Scheduling for Animations 95
Testing with Schedulers 97
Wrapping Up 101

6. Reactive Web Applications with Cycle.js . . . . . 103


Cycle.js 103
Installing Cycle.js 104
Our Project: Wikipedia Search 105
Model-View-Intent 112
Creating Reusable Widgets 115
Ideas for Improvements 118
Wrapping Up 118

Index . . . . . . . . . . . . . . 119
Acknowledgments
I have so many people to thank. There are those who have helped shape the
book and those who have helped shape me as a person. I couldn’t have done
this without any of them. I would particularly like to thank the following:

The exceptional people who came up with the Reactive Extensions library in
the first place, and the ones who expanded and evangelized it. This book
would obviously not exist without you: Erik Meijer, Matt Podwysocki, Bart
De Smet, Wes Dyer, Jafar Husain, André Staltz, and many more I am probably
forgetting.

The folks at The Pragmatic Bookshelf. It has been a pleasure to work with
you. Special thanks to Susannah Pfalzer, who has believed in the book since
it was nothing but an idea. I was also extremely lucky to get Rebecca Gulick
as my editor: You have been professional, patient, attentive to my questions,
and a joy to work with. I’ve been a fan of Pragmatic’s books for a long time,
and it has been a privilege to write a PragProg book myself. And, yes, both
publishers, Dave Thomas and Andy Hunt, do read and review every book!

The brilliant technical reviewers. David Bock, Javier Collado Cabeza, Fred
Daoud, Irakli Gozalishvili, Zef Hemel, Ramaninder Singh Jhajj, Aaron Kalair,
Daniel Lamb, Brian Schau, and Stephen Wolff, as well as Pragmatic publishers
Dave and Andy: This book is infinitely better thanks to all of you. You each
selflessly put time and energy into reviewing this book, detecting complicated
errors and saving me from more than one embarrassing mistake. Any errors
remaining in the book are my own fault.

To my friends. The ones who are always there, no matter the time and the
distance; you know who you are. Thanks for the laughs, the support, the
love.

My parents, Narcís Mansilla and Joana Molins. You are my guides and role
models. You never ceased to believe in me and always encouraged me to take
on bigger challenges. You bought me my first computer at a time when you
struggled to pay the bills. That started it all, and I owe you everything.

report erratum • discuss


Acknowledgments •x

My son, Adrià. You were born while I was writing this book, and you have
changed the meaning of life for me. You’ve already taught me so much in
such little time, and I can’t wait to see what’s next.

Finally, Jen, the love of my life. You have had infinite patience and supported
me while I wrote a book in one of the busiest periods of our life so far. You
are an inspiration to me and you make me a better human being in every
way. You are my star.

Sergi Mansilla
Barcelona, December 2015

report erratum • discuss


Preface
Reactive programming is taking the software world by storm. This book
combines the reactive programming philosophy with the possibilities of
JavaScript, and you’ll learn how to apply reactive techniques to your own
projects. We’ll focus on reactive programming to manage and combine streams
of events. In fact, we’ll cover how to make entire real-world, concurrent
applications just by declaring transformations on our program’s events.

Most software today deals with data that’s available only over time: websites
load remote resources and respond to complex user interactions, servers are
distributed across multiple physical locations, and people have mobile devices
that they expect to work at all times, whether on high-speed Wi-Fi or spotty
cellular networks. Any serious application involves many moving asynchronous
parts that need to be efficiently coordinated, and that’s very hard with today’s
programming techniques. On top of that, we have what’s always been there:
servers crashing, slow networks, and software bugs we have to deal with.

We can’t afford to keep programming applications the way we always have.


It worked for a while, but now it’s time for a new approach.

New World, Old Methods


In recent years JavaScript has become the most ubiquitous language in the
world and now powers the mission-critical infrastructure of businesses such
as Walmart and Netflix,1 mobile operating systems such as Firefox OS, and
complex popular applications such as Google Docs.

And yet we’re still using good ol‘ imperative-style programming to deal with
problems that are essentially asynchronous. This is very hard.

JavaScript developers see the language’s lack of threads as a feature, and we


usually write asynchronous code using callbacks, promises, and events. But

1. http://venturebeat.com/2012/01/24/why-walmart-is-using-node-js/, http://techblog.netflix.com/2014/06/scale-
and-performance-of-large.html

report erratum • discuss


Preface • xii

as we keep adding more concurrency to our applications, the code to coordi-


nate asynchronous flows becomes unwieldy. Current mechanisms all have
serious shortcomings that hinder the developer’s productivity and make for
fragile applications.

Here’s a quick rundown of the current mechanisms for handling asynchronous


operations, along with their problems.

Callback Functions
A callback is a function (A) passed as a parameter to another function (B) that
performs an asynchronous operation. When (B) is done, it calls back (A) with
the results of the operation. Callbacks are used to manage asynchronous
flows such as network I/O, database access, or user input.
intro/callback_example.js
function B(callback) {
// Do operation that takes some time
callback('Done!');
}

function A(message) {
console.log(message);
}

// Execute `B` with `A` as a callback


B(A);

Callbacks are easy to grasp and have become the default way of handling
asynchronous data flows in JavaScript. But this simplicity comes at a price.
Callbacks have the following drawbacks:

• Callback hell. It’s easy to end up with lots of nested callbacks when han-
dling highly asynchronous code. When that happens, code stops being
linear and becomes hard to reason about. Whole applications end up
passed around in callbacks, and they become difficult to maintain and
debug.

• Callbacks can run more than once. There’s no guarantee the same callback
will be called only once. Multiple invocations can be hard to detect and
can result in errors and general mayhem in your application.

• Callbacks change error semantics. Callbacks break the traditional try/catch


mechanism and rely on the programmer to check for errors and pass
them around.

report erratum • discuss


New World, Old Methods • xiii

• Concurrency gets increasingly complicated. Combining interdependent


results of multiple asynchronous operations becomes difficult. It requires
us to keep track of the state of each operation in temporal variables, and
then delegate them to the final combination operation in the proper order.

Promises
Promises came to save us from callbacks. A promise represents the result of
an asynchronous operation. In promise-based code, calling an asynchronous
function immediately returns a “promise” that will eventually be either resolved
with the result of the operation or rejected with an error. In the meantime,
the pending promise can be used as a placeholder for the final value.

Promises usually make programs more clear by being closer to synchronous


code, reducing the need for nesting blocks and keeping track of less state.

Unfortunately, promises are not a silver bullet. They’re an improvement over


callbacks, but they have a major shortcoming: they only ever yield a single
value. That makes them useless for handling recurrent events such as mouse
clicks or streams of data coming from the server, because we would have to
create a promise for each separate event instead of creating a promise that
handles the stream of events as it comes.

Event Emitters
When we emit an event, event listeners that are subscribed to it will fire.
Using events is a great way to decouple functionality, and in JavaScript, event
programming is common and generally a good practice.

But, you guessed it, event listeners come with their own set of problems, too:

• Events force side effects. Event listener functions always ignore their
return values, which forces the listener to have side effects if it wants to
have any impact in the world.

• Events are not first-class values. For example, a series of click events can’t
be passed as a parameter or manipulated as the sequence it actually is.
We’re limited to handling each event individually, and only after the event
happens.

• It is easy to miss events if we start listening too late. An infamous example


of that is the first version of the streams interface in Node.js, which would
often emit its data event before listeners had time to listen to it, losing it
forever.

report erratum • discuss


Preface • xiv

Since these mechanisms are what we’ve always used to manage concurrency,
it might be hard to think of a better way. But in this book I’ll show you one:
reactive programming and RxJS try to solve all these problems with some
new concepts and mechanisms to make asynchronous programming a breeze
—and much more fun.

What Is Reactive Programming?


Reactive programming is a programming paradigm that encompasses many
concepts and techniques. In this book I’ll focus particularly on creating,
transforming, and reacting to streams of data. Mouse clicks, network requests,
arrays of strings—all these can be expressed as streams to which we can
“react” as they publish new values, using the same interfaces regardless of
their source.

Reactive programming focuses on propagating changes without our having


to explicitly specify how the propagation happens. This allows us to state
what our code should do, without having to code every step to do it. This
results in a more reliable and maintainable approach to building software.

What Is RxJS?
RxJS is a JavaScript implementation of the Reactive Extensions, or Rx.2 Rx
is a reactive programming model originally created at Microsoft that allows
developers to easily compose asynchronous streams of data. It provides a
common interface to combine and transform data from wildly different sources,
such as filesystem operations, user interaction, and social-network updates.

Rx started with an implementation for .NET, but today it has a well-maintained


open source implementation in every major language (and some minor ones).
It is becoming the standard to program reactive applications, and Rx’s main
data type, the Observable, is being proposed for inclusion in ECMAScript 7
as an integral part of JavaScript.

Who This Book Is For


This book is for developers with some experience with JavaScript. You should
be comfortable with closures and higher-order functions, and you should
understand the scope rules in JavaScript. That being said, I try to explain
the most complex language concepts we go through in this book.

2. https://rx.codeplex.com/

report erratum • discuss


What’s in This Book • xv

What’s in This Book


This book is a practical introduction to reactive programming using RxJS.
The objective is to get you to think reactively by building small real-world
applications, so you can learn how to introduce reactive programming in your
day-to-day programming and make your programs more robust. This is not
a theoretical book about reactive programming, and it is not an exhaustive
reference book for the RxJS API. You can find these kinds of resources online.

We’ll be developing mostly for the browser, but we’ll see some examples in
Node.js, too. We’ll get deep into the subject early on, and we’ll build applica-
tions along the way to keep it real. Here are the chapters:

Unless you have used RxJS before, start with Chapter 1, The Reactive Way,
on page 1. In this chapter we introduce Observables, the main data type of
RxJS, which we’ll use extensively throughout the book.

With the basics of Observables established, we move on to Chapter 2, Deep


in the Sequence, on page 17. There you see that in reactive programming it’s
all about sequences of events. We visit some important sequence operators
and we build our first application, a real-time earthquake visualizer.

In Chapter 3, Building Concurrent Programs, on page 39, we look at how to


write concurrent code with minimal side effects. After covering the Observable
pipeline, we build a cool spaceship video game in about 200 lines of code and
with almost no global state.

In Chapter 4, Building a Complete Web Application, on page 69, we get deeper


into reactive app development and enhance the earthquake application we
made previously in Deep in the Sequence by making a server part in Node.js
that shows tweets related to earthquakes happening right now.

We get into some more advanced concepts of RxJS with Chapter 5, Bending
Time with Schedulers, on page 89, where we talk about the useful concept
RxJS provides to handle concurrency at a more fine-grained level: Schedulers.

With the knowledge of Schedulers under our hats, we explore how they help
us with testing. We’ll see how to simulate time in our tests to accurately test
asynchronous programs.

Finally, in Chapter 6, Reactive Web Applications with Cycle.js, on page 103,


we’ll use Cycle.js, a UI framework built on top of RxJS, to build a simple
application. Cycle.js draws concepts from modern frameworks such as React.js
to create a reactive framework that uses the advantages of Observables to
help us create fast user interfaces in a simple and reliable way.

report erratum • discuss


Preface • xvi

Running the Code Examples


The code examples in this book are made for either the browser or Node.js.
The context of the code should clarify in what environment to run the code.

Running RxJS Code in the Browser


If the code is meant to run in the browser, we’ll use the file rx.all.js, which you
can find in the RxJS GitHub repository.3 rx.all.js includes all the operators in
RxJS, and it’s the easiest way to be sure all examples will work. Just load
the script in the <head> section of your HTML document:
<html>
<head>
<script src="rx.all.js"></script>
</head>
...
</html>

Keep in mind that it is a relatively big file and you may want to consider a
smaller file, such as rx.js or rx.lite.js, for your projects if you’re not using all the
functionality in RxJS.

Running RxJS Code in Node.js


Running code examples in Node.js is easy. Just make sure you install the
RxJS dependency in your project using npm:
$ npm install rx
rx@4.0.0 node_modules/rx

After that, you can import the RxJS library in your JavaScript files:
var Rx = require('rx');

Rx.Observable.just('Hello World!').subscribe(function(value) {
console.log(value);
});

And you can run it by simply invoking node and the name of the file:
$ node test.js
Hello World!

3. https://github.com/Reactive-Extensions/RxJS/tree/master/dist

report erratum • discuss


Resources • xvii

RxJS Version
All the examples are made for RxJS 4.x. You can download the latest version
in the RxJS online repository.4

Resources
RxJS is gaining adoption very quickly, and there are more and more resources
about it every day. At times it might be hard to find resources about it online,
though. These are my favorite ones:

• RxJS official source code repository5

• ReactiveX, a collection of resources related to the Reactive Extensions6

• RxMarbles, an interactive tool to visualize Observables7

Download Sample Code


This book’s website has links to an interactive discussion forum as well as a
place to submit errata.8 You’ll also find the source code for all the projects
we build. Readers of the ebook can interact with the box above each code
snippet to view that snippet directly.

4. https://github.com/Reactive-Extensions/RxJS/releases/latest
5. https://github.com/Reactive-Extensions/RxJS
6. http://reactivex.io
7. http://rxmarbles.com/
8. http://pragprog.com/titles/smreactjs

report erratum • discuss


CHAPTER 1

The Reactive Way


The real world is pretty messy: events happen in random order, applications
crash, and networks fail. Few applications are completely synchronous, and
writing asynchronous code is necessary to keep applications responsive. Most
of the time it’s downright painful, but it really doesn’t have to be.

Modern applications need super-fast responses and the ability to process


data from different sources at the same time without missing a beat. Current
techniques won’t get us there because they don’t scale—code becomes expo-
nentially more complex as we add concurrency and application state. They
get the job done only at the expense of a considerable mental load on the
developer, and that leads to bugs and complexity in our code.

This chapter introduces you to reactive programming, a natural, easier way


to think about asynchronous code. I’ll show you how streams of events—
which we call Observables—are a beautiful way to handle asynchronous code.
Then we’ll create an Observable and see how reactive thinking and RxJS
dramatically improve on existing techniques and make you a happier, more
productive programmer.

What’s Reactive?
Let’s start by looking at a little reactive RxJS program. This program needs
to retrieve data from different sources with the click of a button, and it has
the following requirements:

• It must unify data from two different locations that use different JSON
structures.

• The final result should not contain any duplicates.

• To avoid requesting data too many times, the user should not be able to
click the button more than once per second.

report erratum • discuss


Discovering Diverse Content Through
Random Scribd Documents
de neuf, le monastère n'a pas la majesté de ses aînés, des antiques
maisons de prière, vouées par la piété des ancêtres à l'observance
de Saint-Bernard. Mais à défaut de la patine des siècles, à défaut du
prestige que donnent aux vieilles murailles, les souvenirs, les
légendes du passé, il offrait à Gilbert le spectacle, plus émouvant
encore, d'une protestation, d'un défi porté par la pérennité de la
pensée chrétienne à l'invasion du monde moderne. C'était, dans le
tumulte d'une société vouée à la conquête de l'argent et du plaisir,
comme une enclave de sacrifice, une île de silence.
De là-haut, le voyageur pouvait suivre le plan, le développement
de l'édifice, il reconnaissait l'hôtellerie en avant, avec son entrée
particulière, il devinait les fenêtres du réfectoire, du dortoir, le
vaisseau de la chapelle, les baies vitrées des ateliers. Plus
longuement, son regard s'arrêtait sur le petit clos consacré à la
sépulture des trappistes, et d'avance, il marquait sa place à côté des
autres, la bonne place où bercé par les psalmodies des offices, il
dormirait son dernier sommeil.
Le verger, le potager s'étendaient autour, égayaient de leur
verdure rectiligne la sévérité des murailles. Tête nue, sous le soleil,
quelques trappistes s'occupaient aux travaux du jardinage ; Gilbert
discernait leurs mouvements, leurs attitudes ; il entendait sonner le
fer de leur bêche repoussée par la glèbe caillouteuse. Bientôt je
bêcherai, je sarclerai comme eux songeait-il. Et il les accompagnait
en pensée, au réfectoire devant l'assiette de haricots ou de pois
chiches, au dortoir, dans une de ces pauvres cellules dont il
apercevait l'alignement dans l'ouverture des croisées.
Lente et grêle, tout à coup une cloche tinta. Les trappistes
quittèrent leurs outils, entrèrent dans la chapelle. C'est l'heure de
complies ; ils vont psalmodier leur office, se disait Gilbert. Et comme
s'il obéissait à l'appel de la règle, il se mit à descendre la colline.
Lentement. Il s'attardait aux rencontres de la route, aux menus
incidents de cette vie extérieure, qu'il allait quitter pour la mort
volontaire du couvent. Une bande de trimardeurs dévalait en même
temps que lui vers la combe ; ventres creux en quête de la sportule.
Des hobereaux du voisinage, piqueur en tête, traversaient la route
avec leur meute, lancée à la conquête d'un lièvre. Ils excitaient les
chiens avec des voix de colère, et la joie prochaine du meurtre
tendait leurs muscles, luisait dans leurs yeux, ingénue et brutale. Un
garçon de ferme occupé à défoncer un ratouble, avait déserté la
charrue pour galantiser avec une pastoure, qui filait sa quenouille,
accroupie dans l'herbe d'une friche.
Voilà donc, pensait Gilbert, l'aboutissement, après combien de
siècles, de ce qu'on appelle le progrès! Des gentilhommes gavés de
bonne chère poursuivent une misérable proie, comme leurs ancêtres
affamés de l'âge de pierre ; un mâle rôde autour de sa femelle,
couple docile à l'instinct ; de pauvres hères, éclopés de l'usine ou
victimes des assommoirs, s'en vont, quêtant leur subsistance de
porte en porte ; ils feront leur lit, ce soir dans l'herbe d'un fossé ou
entre les murs d'une prison. Et c'est tout ce que l'homme a su faire
pour l'homme! Gilbert avait mis une aumône dans la main d'un des
mendiants qui l'escortaient ; ses compagnons de misère aussitôt
l'assaillirent, exigeant le partage. Il y eut une bousculade, des
horions, des injures. Puis ce fut le tour des chasseurs ; un coup de
fusil partit à la lisière des bois, annonça la mort du lièvre ; des
cuivres éclatèrent en fanfare, signalèrent ce triomphe. Et, dans la
friche, en se retournant, Gilbert aperçut les deux rustres, le garçon
de charrue, la gardeuse de moutons, qui s'accolaient. Beau
spectacle! Le spectateur eut une grimace de dégoût. Et pourtant, la
veille encore, sur le banc du jardin, à Encrambade, n'était-ce pas la
même folie qui le tenait, n'était-ce pas le même geste?
Oh! le refuge ; vite! la sécurité du mur entre la femme et lui!
L'épreuve finissait. Gilbert touchait au seuil du monastère.
Dévotement, amoureusement, il s'agenouilla, il posa ses lèvres sur le
bois de cette porte qui allait lui ouvrir le monde de la pureté, le
monde de la Grâce.
Ce fut son baiser de fiançailles avec le cloître.

FIN
Arcis-sur-Aube. — Typ. Frémont
NOTE DU TRANSCRIPTEUR
La publication dans la Revue Blanche en 1899-1900
comprenait trois parties séparées en chapitres. L'édition en
volume a retiré la séparation en parties, et renuméroté les
chapitres de I à XXVI, à l'exception du chapitre V de la
troisième partie, oublié lors de la renumérotation.
On a retiré la mention "première partie" qui restait en
tête du premier chapitre, et repris la numérotation des
chapitres à partir de ce chapitre V de la troisième partie,
qui devient le chapitre XXI.
*** END OF THE PROJECT GUTENBERG EBOOK LE VŒU D'ÊTRE
CHASTE: ROMAN ***

Updated editions will replace the previous one—the old editions will
be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying
copyright royalties. Special rules, set forth in the General Terms of
Use part of this license, apply to copying and distributing Project
Gutenberg™ electronic works to protect the PROJECT GUTENBERG™
concept and trademark. Project Gutenberg is a registered trademark,
and may not be used if you charge for an eBook, except by following
the terms of the trademark license, including paying royalties for use
of the Project Gutenberg trademark. If you do not charge anything
for copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived


from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted


with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this


electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the Project
Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing


access to or distributing Project Gutenberg™ electronic works
provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for


the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,


the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West,


Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many
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!

ebookfinal.com

You might also like