SlideShare a Scribd company logo
Download the full version of the textbook now at textbookfull.com
Rx.NET in Action with Examples in C# 1st
Edition Tamir Dresher
https://textbookfull.com/product/rx-net-in-action-
with-examples-in-c-1st-edition-tamir-dresher/
Explore and download more textbook at https://textbookfull.com
Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.
C++20 in Examples. 1st Edition Alex Vasilev
https://textbookfull.com/product/c20-in-examples-1st-edition-alex-
vasilev/
textbookfull.com
Spark in Action - Second Edition: Covers Apache Spark 3
with Examples in Java, Python, and Scala Jean-Georges
Perrin
https://textbookfull.com/product/spark-in-action-second-edition-
covers-apache-spark-3-with-examples-in-java-python-and-scala-jean-
georges-perrin/
textbookfull.com
R in Action Data Analysis and Graphics with R Bonus ch 23
ONLY 2nd Edition Robert Kabacoff
https://textbookfull.com/product/r-in-action-data-analysis-and-
graphics-with-r-bonus-ch-23-only-2nd-edition-robert-kabacoff/
textbookfull.com
Advances in Transitional Flow Modeling Applications to
Helicopter Rotors 1st Edition Chunhua Sheng (Auth.)
https://textbookfull.com/product/advances-in-transitional-flow-
modeling-applications-to-helicopter-rotors-1st-edition-chunhua-sheng-
auth/
textbookfull.com
Nephrology Worldwide 1st Edition José A. Moura-Neto
(Editor)
https://textbookfull.com/product/nephrology-worldwide-1st-edition-
jose-a-moura-neto-editor/
textbookfull.com
An Introduction to Management Science: Quantitative
Approach David R. Anderson & Dennis J. Sweeney & Thomas A.
Williams & Jeffrey D. Camm & James J. Cochran
https://textbookfull.com/product/an-introduction-to-management-
science-quantitative-approach-david-r-anderson-dennis-j-sweeney-
thomas-a-williams-jeffrey-d-camm-james-j-cochran/
textbookfull.com
Cultural Anthropology: Appreciating Cultural Diversity
Conrad Phillip Kottak
https://textbookfull.com/product/cultural-anthropology-appreciating-
cultural-diversity-conrad-phillip-kottak/
textbookfull.com
Practical Business Negotiation 2nd Edition William W.
Baber (Author)
https://textbookfull.com/product/practical-business-negotiation-2nd-
edition-william-w-baber-author/
textbookfull.com
Dental Radiography Principles and Techniques Iannucci Dds
Ms
https://textbookfull.com/product/dental-radiography-principles-and-
techniques-iannucci-dds-ms/
textbookfull.com
Topological Vector Spaces and Their Applications 1st
Edition V.I. Bogachev
https://textbookfull.com/product/topological-vector-spaces-and-their-
applications-1st-edition-v-i-bogachev/
textbookfull.com
Rx.NET in Action
TAMIR DRESHER
M A N N I N G
SHELTER ISLAND
ISBN 9781617293061
Printed in the United States of America
©2017 by Manning Publications Co.
contents
foreword xi
preface xiii
acknowledgments xv
about this book xvii
about the author xxi
about the cover illustration xxii
PART 1 GETTING STARTED WITH REACTIVE
EXTENSIONS .................................................... 1
1 Reactive programming 3
1.1 Being reactive 4
Reactiveness in your application 6
1.2 Introducing Reactive Extensions 7
Rx history 8 ■
Rx on the client and server 9
Observables 10 ■
Operators 12 ■
The composable
nature of Rx operators 13 ■
Marble diagrams 14
Pull model vs. push model 15
1.3 Working with reactive systems and the Reactive
Manifesto 17
Responsiveness 17 ■
Resiliency 18 ■
Elasticity 18
Message driven 19 ■
Where is Rx? 20
1.4 Understanding asynchronicity 20
It’s all about resource use 21 ■
Asynchronicity and Rx 23
1.5 Understanding events and streams 24
Everything is a stream 24
1.6 Summary 26
2 Hello, Rx 27
2.1 Working with traditional .NET events 28
Dealing with concurrency 33 ■
Retrospective on the solution
and looking at the future 35
2.2 Creating your first Rx application 39
Selecting Rx packages 39 ■
Installing from NuGet 42
2.3 Writing the event-processing flow 44
Subscribing to the event 44 ■
Grouping stocks by symbol 45
Finding the difference between ticks 46 ■
Cleaning
resources 49 ■
Dealing with concurrency 50
Wrapping up 50
2.4 Summary 52
3 Functional thinking in C# 54
3.1 The advantages of thinking functionally 55
Declarative programming style 55 ■
Immutability and side
effects 56 ■
First-class functions 58 ■
Being concise 59
3.2 First-class and higher-order functions using
delegates and lambdas 59
Delegates 60 ■
Anonymous methods 61 ■
Lambda
expressions 63 ■
Func and Action 64 ■
Using it all
together 66
3.3 Method chaining with extension methods 70
Extending type behavior with extension methods 70
Fluent interfaces and method chaining 72 ■
Creating a
language 74
3.4 Querying collections with LINQ 75
What does LINQ look like? 77 ■
Nested queries and joins 78
Anonymous types 79 ■
LINQ operators 81 ■
Efficiency by
deferred execution 83
3.5 Summary 86
PART 2 CORE IDEAS ................................................... 87
4 Creating observable sequences 89
4.1 Creating streams of data and events with observables 90
Implementing the IObservable<T> interface 90 ■
The problem with
handcrafted observables 93 ■
The ObservableBase 93
Creating observables with Observable.Create 96 ■
Deferring the
observable creation 97
4.2 Creating observables from events 99
Creating observables that conform to the EventPattern 99
Events that aren’t following the event pattern 102
Events with multiple parameters 102 ■
Dealing with events
that have no arguments 104
4.3 From enumerables to observables and back 104
Enumerable to observable 105 ■
Observable to enumerable 107
4.4 Using Rx creational operators 110
Generating an observable loop 110 ■
Reading a file 111
The primitive observables 112
4.5 Summary 113
5 Creating observables from .NET asynchronous types 115
5.1 Bridging .NET asynchronous types with Rx 116
Changing the synchronous method to asynchronous 117
Creating the primes observable 117 ■
Using async-await in
observable creation 121 ■
Converting tasks to observables 122
Running asynchronous code as part of the pipeline 124
Controlling the results order 128
5.2 Creating observables of periodic behavior 130
Emitting values in time intervals 130 ■
Creating an observable
timer 131 ■
Scheduling an emission with a timer 132
5.3 Summary 134
6 Controlling the observer-observable relationship 135
6.1 Creating observers 136
The observable-observer communication 136 ■
Creating observers
without leaving the pipeline 137 ■
Not passing OnError and
asynchronous observables 139 ■
Replacing the subscription
disposal with cancellation 140 ■
Creating an observer
instance 141
6.2 Controlling the observable-observer relationship lifetime 142
Delaying subscription 143 ■
Stop emitting notifications at a
scheduled time 145 ■
Discarding items when another observable
emits 145 ■
Skipping notifications 147 ■
Taking or stopping
when a condition is met 148 ■
Resubscribing 150 ■
Adding
side effects in the observable pipeline 151
6.3 Putting it all together 153
6.4 Summary 155
7 Controlling the observable temperature 157
7.1 Multicasting with subjects 158
Simple broadcasting with Subject<T> 160 ■
Representing
asynchronous computation with AsyncSubject 163
Preserving the latest state with BehaviorSubject 165
Caching the sequence with ReplaySubject 166 ■
Hiding your
subjects 167 ■
Following best practices and guidelines 169
7.2 Introducing temperature: cold and hot observables 169
Explaining cold and hot observables 170 ■
Cold observable 171
Hot observables 171
7.3 Heating and cooling an observable 171
Turning cold into hot 171 ■
Using ConnectableObservable 174
Publishing and multicasting 175 ■
Using Multicast 178
Managing the ConnectableObservable connection 179
Cooling a hot observable to allow replaying 181
7.4 Summary 183
8 Working with basic query operators 184
8.1 Selecting what’s important (mapping) 185
8.2 Flattening observables 187
Flattening observables of enumerables 187 ■
Flattening observables
of observables 190
8.3 Filtering an observable 192
Filtering with the Where operator 192 ■
Creating a distinct
sequence 193 ■
Removing duplicate contiguous values 195
8.4 Aggregating the observable sequence 196
Using basic aggregation operators 196 ■
Finding the maximum
and minimum items by condition 200 ■
Writing your aggregation
logic with Aggregate and Scan 201
8.5 Summary 203
9 Partitioning and combining observables 205
9.1 Combining observables 206
Pairing items from observables (zipping) 206 ■
Combining
the latest emitted values 207 ■
Concatenating
observables 208 ■
Merging observables 209 ■
Dynamic
concatenating and merging 210 ■
Switching to the next
observable 212
9.2 Grouping elements from the observable 214
9.3 Joining observables (coincidence-based combining) 215
Joining to a flat stream 215 ■
Joining into groups 219
9.4 Buffers and sliding windows 221
Buffering 222 ■
Windowing the observable sequence 226
9.5 Summary 229
10 Working with Rx concurrency and synchronization 231
10.1 Controlling concurrency with schedulers 231
Defining the scheduler 232 ■
Parameterizing concurrency 235
Types of schedulers 237
10.2 Using time-based operators 241
Adding a timestamp to a notification 242 ■
Adding the time
interval between notifications 243 ■
Adding a time-out
policy 244 ■
Delaying the notifications 245 ■
Throttling
the notifications 247 ■
Sampling the observable
in intervals 249
10.3 Synchronizing the observable emissions 250
Changing the observation’s execution context 250 ■
Changing the
subscription/unsubscription execution context 251 ■
Using
SubscribeOn and ObserveOn together 253 ■
Synchronizing
notifications 255
10.4 Summary 257
11 Error handling and recovery 259
11.1 Reacting to errors 260
Errors from the observable side 260 ■
Catching errors 262
Retrying to subscribe in case of an error 264
11.2 Controlling the lifetime of resources 265
Disposing in a deterministic way 266 ■
Deterministic
finalization 269 ■
Dangling observers 270
11.3 Dealing with backpressure 276
Observables of different rates 276 ■
Mitigating backpressure 278
11.4 Summary 279
appendix A Writing asynchronous code in .NET 281
appendix B The Rx Disposables library 291
appendix C Testing Rx queries and operators 298
index 313
foreword
This book, Rx.NET in Action, does a great job in explaining the details and back-
ground that .NET developers need to effectively use Rx. In particular, it explains how
to connect the plethora of asynchronous types in .NET to Rx observables, and how to
deal with errors, resource allocation, and last but not least, concurrency.
Since its inception, the .NET Framework has emphasized the importance of asyn-
chronous execution and nonblocking I/O. Through delegates, the .NET Framework
has emphasized higher-order functional programming from the beginning, and by
automatically defining the BeginInvoke and EndInvoke methods on delegates, devel-
opers may call any method asynchronously.
But the BeginInvoke/EndInvoke pattern for asynchronous operations is tedious
and verbose, because it requires converting your code into continuation-passing style.
As an alternative, the .NET Framework introduced the event-based asynchronous pat-
tern that uses the built-in support of .NET for events and event handlers. Although the
event-based pattern was a big step forward compared to asynchronous delegates, more
opportunities remained to streamline the development experience.
For synchronous streams of values, modeled by the standard interfaces of Enumer-
able/IEnumerator, the LINQ standard query operators provide a beautiful and ele-
gant algebra for processing streams in a high-level and declarative manner. Wouldn’t
it be nice if we could use the fact that events are conceptually also streams of values
and hence provide a similar LINQ-based programming model for events?
Another disadvantage of using events for asynchronous calls is that this ignores the
fact that unlike most other events, such as mouse clicks, the events wired up to asyn-
chronous operations produce at most one value. Wouldn’t it be nice if we could use
the fact that asynchronous methods return only a single value and hence provide a
similar imperative programming model that supports regular control-flow-like condi-
tionals, loops, and exception handling for asynchronous methods?
As it turns out, the answer to both questions is a resounding yes! By using the
mathematical trick of equalization, we can mechanically convert the IEnumerable
/IEnumerator interfaces for synchronous pull-based streams into the monadic
IObservable/IObserver interfaces for asynchronous push-based streams. The
async/await syntax in C# and Visual Basic allows developers to use regular imperative
syntax to write both synchronous and asynchronous methods, and the LINQ query
comprehensions allow developers to write queries over both synchronous and asyn-
chronous data streams
This is the heart of Rx. Many languages outside the .NET world have now adopted
the magic square of one/many × sync/async, making developers happy and produc-
tive no matter what language they’re using.
If you’re a .NET developer, you’ll want to keep a copy of this book handy to put
Rx.NET into action!
—ERIK MEIJER
INVENTOR OF RX, FOUNDER OF APPLIED DUALITY
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
preface
Reactive Extensions (Rx) for .NET was first published in November 2009 under the
short description “Rx is a .NET Library that allows programmers to write succinct
declarative code to orchestrate and coordinate asynchronous and event-based pro-
grams based on familiar .NET idioms and patterns.” (See http://mng.bz/gQ31.)
I remember watching the first examples and reading the discussions. I was amazed
by the elegance of the solutions and how simple they looked. Unfortunately, when I
sat down and tried to use Rx, things were harder than I thought, and the mental
change I needed to make toward reactive programming was significant. In those days,
there wasn’t a lot of material on the subject, and I had to struggle to solve my issues
and learn things the hard way with a lot of trial and error.
In 2012, at end of my military service and upon joining CodeValue (www.code-
value.net), I had two major projects that enabled me to really appreciate my Rx knowl-
edge. The first was about a cybersecurity application that needed to react to multiple
events and coordinate them in order to show the end user the state of various inci-
dents all happening in parallel. The second was a video chat application, running on
mobile and PC devices. The video chat application reacted to events such as users log-
ging in and out of the system and receiving messages of various types that had to be
dealt with differently. Though these two systems were different, they shared the same
problems of writing a flow based on events—a flow that involves filtering of received
values, dealing with asynchronicity and concurrency, and identifying patterns of recur-
ring events so that the application could respond efficiently and correctly. I intro-
duced Rx to both of those systems, and it was one of the things that made each a
success. We exceeded expectations and preceded our schedule.
Still, even though I had knowledge of Rx, problems still happened from time to
time, and little material on Rx, such as books and guides, was available. Many times
problems originated because of my colleagues’ lack of knowledge or situations that
were new to us. Luckily, after I identified the problem source, it would be easy to fix,
mostly because of the flexibility of Rx operators. In the following years, I started to
blog and speak about Rx and how it made solving complex problems easy. That is
when the idea for this book started to grow. My vision was to create a step-by-step
guide that holds the pieces needed for the .NET programmer to get the maximum out
of the Rx library and the reactive programming paradigm. I also wanted to write about
the practices that I acquired over the years, as well as the pitfalls and their solutions.
It took hard and careful work to make sure the book fulfills its aim. Some chapters
had to be rewritten, topics were changed, and some material had to be left out in
order to concentrate on the important and fundamental features. The result of this
hard work is Rx.NET in Action, a book that you can read front to back or go directly to
a specific chapter to solve a problem or refresh your memory.
Rx is an evolving technology that was also ported to numerous other platforms and
languages. It is an open source project and part of the .NET Foundation (www.dotnet-
foundation.org). My hope is that Rx will become the de facto way to program, orches-
trate, and coordinate asynchronous and event-based programs in .NET and that this
book will give you everything you need to be ready for this new and exciting world of Rx.
about this book
Rx.NET in Action is a full guide for the Reactive Extensions library for .NET developers.
It delivers explanations, best practices, and tips and tricks that will allow you to fully
use Rx in your applications.
Who should read this book
Rx.NET in Action is for .NET developers who write event-based and asynchronous
applications and need powerful consuming and querying capabilities over events and
push-based sources.
Rx.NET in Action is also suitable for developers who are curious about reactive pro-
gramming and the Rx library techniques, but who may not have an immediate need to
use it. Adding Rx know-how to your toolbox is valuable for future projects; reactive
programing is a hot topic and will continue to be in the future.
This book primarily uses the .NET version of Rx, and the code examples use the C#
language. Readers familiar with C# will be right at home.
This book is suitable for any platform supported by .NET (including .NET Core).
How this book is organized
The book’s 11 chapters are divided into two sections.
Part 1 provides an introduction to reactive programming and to the .NET skills you
need in order to understand the functional aspects of the library.
 Chapter 1 explores the reactive programming paradigm and Reactive Mani-
festo concepts. The chapter introduces the building blocks of Rx and explains
when and why it should be used.
 Chapter 2 is where you really meet Rx and the steps needed to incorporate it into
your application. It shows a simple case-study of using Rx inside an application
and compares two versions of the same application, before and after Rx is used.
 Chapter 3 provides an overview of the functional programming concepts and
techniques that Rx uses and how they’re provided with the .NET Framework
and the C# language.
Part 2 dives into each of the tasks you’ll do with Rx—from creating observables and
observers, to controlling their lifetimes and reacting to queries you create on top of
them.
 Chapter 4 teaches ways to create observable sequences and it shows how syn-
chronous observables can be created from enumerables and built-in creation
operators.
 Chapter 5 explains the way Rx handles asynchronous code and how to bridge
the native .NET asynchronous types into observables. This chapter also discusses
the importance of asynchronous code in the modern application and how to
add periodic behavior to your programs.
 Chapter 6 concentrates on the observable-observer relationship and how to
control it. In this chapter, I explain the best way to create observers for various
scenarios and how to limit the lifetime of the observer subscription.
 Chapter 7 explains the differences between hot and cold observables and intro-
duces Rx subjects. This chapter teaches you how to control the state of the
observable when observers subscribe to it and how to share emissions between
the observers.
 Chapter 8 provides a catalog of the basic query operators provided in the Rx
library. Rx is often referred to as LINQ to Events, and knowing the details of the
Rx operators will help you build powerful queries that will save you time and
effort.
 Chapter 9 continues where chapter 8 leaves off and shows advanced ways to par-
tition and combine observables. You’ll learn how to group elements by condi-
tion or by coincidence and how to react to correlations between observables.
 Chapter 10 delves deep into the Rx concurrency model and synchronization. I
introduce the concept of schedulers and explain the schedulers Rx has to
offer. Then I explain how to control the time and computation location of
your Rx queries.
 Chapter 11 teaches you to protect your Rx queries from faults and to react to
errors that might happen in the query processing. This chapter also covers ways
to manage resources that are consumed by the observables and the Rx queries.
The book also has three appendices:
 Appendix A summarizes the concepts of asynchronous programming in .NET.
 Appendix B presents the Rx Disposables library and explains how to use the
utilities it provides.
 Appendix C explains how to test Rx operators and queries.
The book is intended to be used as a guide and as a reference. If you’re new to Rx, I
recommend reading from the beginning. If you’re already familiar with Rx concepts,
you might find it useful to read a specific chapter based on the task you’re trying to
accomplish.
About the code
This book contains many examples of source code both in numbered listings and
inline with normal text. In both cases, source code is formatted in a fixed-width
font like this to separate it from ordinary text. Sometimes code is also in bold to
highlight code that has changed from previous steps in the chapter, such as when a
new feature adds to an existing line of code.
In many cases, the original source code has been reformatted; we’ve added line
breaks and reworked indentation to accommodate the available page space in the
book. In rare cases, even this was not enough, and listings include line-continuation
markers (➥). Additionally, comments in the source code have often been removed
from the listings when the code is described in the text. Code annotations accompany
many of the listings, highlighting important concepts.
The source code for this book is available to download from the publisher’s web-
site (www.manning.com/books/rx-dot-net-in-action) and from GitHub (https://
github.com/tamirdresher/RxInAction). Instructions for using this code are provided
in the README file included in the repository root.
In the e-book, color is used in some listings and code snippets. Blue is used for
primitive types and saved keywords. Aqua highlights user-defined types, and red is
used for string literals. Brown is used for string parameters placeholders, and green is
for comments. As always, black is user code.
Author Online
Purchase of Rx.NET in Action includes free access to a private web forum run by Man-
ning Publications, where you can make comments about the book, ask technical ques-
tions, and receive help from the author and from other users. To access the forum
and subscribe to it, point your web browser at www.manning.com/books/rx-dot-net-
in-action. This page provides information on how to get on the forum after you’re reg-
istered, the kinds of help available, and the rules of conduct on the forum.
Manning’s commitment to our readers is to provide a venue where a meaningful
dialogue between individual readers and between readers and the author can take
place. It’s not a commitment to any specific amount of participation on the part of the
author, whose contribution to the Author Online forum remains voluntary (and
unpaid). We suggest you try asking him some challenging questions, lest his interest
stray! The Author Online forum and the archives of previous discussions will be acces-
sible from the publisher’s website as long as the book is in print.
Other online resources
If you’re interested in Rx, you may also want to check out the Rx portal http://
reactivex.io, which provides a Developer Center. It contains the most recent informa-
tion about the library and its ports.
Rx.NET is an open source project, and you can find the full code and discussions at
https://github.com/Reactive-Extensions/Rx.NET.
If you want to ask a question about Rx, you can visit the gitter channel (https://
gitter.im/Reactive-Extensions/Rx.NET) or the slack #rx channel, which requires you
to subscribe through the sign-up page for the .NET Core Slack Channel (http://
tattoocoder.com/aspnet-slack-sign-up/).
Part 1
Getting started with
Reactive Extensions
What are reactive applications? What are they good for? How does pro-
gramming with Reactive Extensions (Rx) change the way you write code? What
should you do before you start working with Rx? And why is Rx better than tradi-
tional event-driven programming? These are the questions we’ll begin to
address in these first three chapters.
You’ll learn what reactive systems and applications are, and why you should
care. You’ll see a real example of creating an application that uses Rx and what
you need to do to create your own Rx applications. You’ll also look at the func-
tional programming foundations that Rx is based on, to make it easier to under-
stand the rest of the concepts that this book introduces.
Reactive programming
The reactive programming paradigm has gained increasing popularity in recent
years as a model that aims to simplify the implementation of event-driven applica-
tions and the execution of asynchronous code. Reactive programming concen-
trates on the propagation of changes and their effects—simply put, how to react to
changes and create data flows that depend on them.1
With the rise of applications such as Facebook and Twitter, every change hap-
pening on one side of the ocean (for example, a status update) is immediately
observed on the other side, and a chain of reactions occurs instantly inside the
application. It shouldn’t come as a surprise that a simplified model to express this
reaction chain is needed. Today, modern applications are highly driven by changes
happening in the outside environment (such as in GPS location, battery and power
management, and social networking messages) as well as by changes inside the
This chapter covers
 Being reactive
 Thinking about events as streams
 Introducing Reactive Extensions (Rx)
1
This book is about reactive programming and not about functional reactive programming (FRP). FRP can
operate on continuous time, whereas Rx can operate only on discrete points of time. More info can be
found at the FRP creator’s keynote, http://mng.bz/TcB6.
4 CHAPTER 1 Reactive programming
application (such as web call responses, file reading and writing, and timers). To all of
those events, the applications are reacting accordingly—for instance, by changing the
displayed view or modifying stored data.
We see the necessity for a simplified model for reacting to events in many types of
applications: robotics, mobile apps, health care, and more. Reacting to events in a clas-
sic imperative way leads to cumbersome, hard-to-understand, and error-prone code,
because the poor programmer who is responsible for coordinating events and data
changes has to work manually with isolated islands of code that can change that same
data. These changes might happen in an unpredictable order or even at the same time.
Reactive programming provides abstractions to events and to states that change over
time so that we can free ourselves from managing the dependencies between those val-
ues when we create the chains of execution that run when those events occur.
Reactive Extensions (Rx) is a library that provides the reactive programming model
for .NET applications. Rx makes event-handling code simpler and more expressive by
using declarative operations (in LINQ style) to create queries over a single sequence of
events. Rx also provides methods called combinators (combining operations) that
enable you to join sequences of events in order to handle patterns of event occur-
rences or the correlations between them. At the time of this writing, more than 600
operations (with overloads) are in the Rx library. Each one encapsulates recurring
event-processing code that otherwise you’d have to write yourself.
This book’s purpose is to teach you why you should embrace the reactive program-
ming way of thinking and how to use Rx to build event-driven applications with ease
and, most important, fun. The book will teach you step by step about the various lay-
ers that Rx is built upon, from the building blocks that allow you to create reactive
data and event streams, through the rich query capabilities that Rx provides, and the
Rx concurrency model that allows you to control the asynchronicity of your code and
the processing of your reactive handlers. But first you need to understand what being
reactive means, and the difference between traditional imperative programming and
the reactive way of working with events.
1.1 Being reactive
As changes happen in an application, your code needs to react to them; that’s what
being reactive means. Changes come in many forms. The simplest one is a change of a
variable value that we’re so accustomed to in our day-to-day programming. The vari-
able holds a value that can be changed at a particular time by a certain operation. For
instance, in C# you can write something like this:
int a = 2;
int b = 3;
int c = a + b;
Console.WriteLine("before: the value of c is {0}",c);
a=7;
b=2;
Console.WriteLine("after: the value of c is {0}",c);
5
Being reactive
The output is
before: the value of c is 5
after: the value of c is 5
In this small program, both printouts show the same value for the c variable. In our
imperative programming model, the value of c is 5, and it will stay 5 unless you over-
ride it explicitly.
Sometimes you want c to be updated the moment a or b changes. Reactive pro-
gramming introduces a different type of variable that’s time varying: this variable isn’t
fixed to its assigned value, but rather the value varies by reacting to changes that hap-
pen over time.
Look again at our little program; when it’s running in a reactive programming
model, the output is
before: the value of c is 5
after: the value of c is 9
“Magically” the value of c has changed. This is due to the change that happened to its
dependencies. This process works just like a machine that’s fed from two parallel con-
veyers and produces an item from the input on either side, as shown in figure 1.1.
5
11
8
9
5
10
1
a:
b:
4
1 2
+
Operator
Reactive
Machine
+
Operator
Reactive
Machine
3
2
7
Figure 1.1 A reactive representation of the function c = a + b. As the values of a and b
are changing, c’s value is changing as well. When a is 7 and b is 2, c automatically changes
to 9. When b changes to 1, c becomes 8 because a’s value is still 7.
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
6 CHAPTER 1 Reactive programming
You might find it surprising, but you’ve probably worked with reactive applications for
years. This concept of reactiveness is what makes your favorite spreadsheet application
so easy and fun to use. When you create this type of equation in a spreadsheet cell,
each time you change the value in cells that feed into the equation, the result in the
final cell changes automatically.
1.1.1 Reactiveness in your application
In a real-world application, you can spot possible time-variant variables in many cir-
cumstances—for instance, GPS location, temperature, mouse coordinates, or even
text-box content. All of these hold a value that’s changing over time, to which the
application reacts, and are, therefore, time variant. It’s also worth mentioning that
time itself is a time variant; its value is changing all the time. In an imperative pro-
gramming model such as C#, you’d use events to create the mechanism of reacting to
change, but that can lead to hard-to-maintain code because events are scattered
among various code fragments.
Imagine a mobile application that helps users find discounts and specials in shops
located in their surrounding area. Let’s call it Shoppy. Figure 1.2 describes the Shoppy
architecture.
Figure 1.2 The Shoppy application architecture. The mobile app receives the current
location from the GPS and can query about shops and deals via the application service.
When a new deal is available, the application service sends a push notification through
the push notifications server.
One of the great features you want from Shoppy is to make the size of the shop icon
bigger on the map as the user gets closer (from a certain minimal radius), as shown in
figure 1.3. You also want the system to push new deals to the application when updates
are available.
SQL
Location
Application
server
Push
notifications
servers
New
deals
Shops
and deals
DB
7
Introducing Reactive Extensions
In this scenario, you could say that the store.Location, myLocation, and icon-
Size variables are time variant. For each store, the icon size could be written:
distance = store.Location – myLocation;
iconSize = (MINIMAL_RADIUS / distance)*MinIconSize
Because you’ve used time-variant variables, each time a change occurs in the
myLocation variable, a change is triggered in the distance variable. The applica-
tion will eventually react by making the store icon appear bigger or smaller, depend-
ing on the distance from the store. Note that for simplicity, I didn’t handle the
boundary check on the minimum allowed icon size, and that distance might be 0 or
close to it.
This is a simple example, but as you’ll see, the great power of using the reactive
programming model lies in its ability to combine and join, as well as to partition and
split the stream of values that each time-variant variable is pushing. This is because
reactive programming lets you focus on what you’re trying to achieve rather than on
the technical details of making it work. This leads to simple and readable code and
eliminates most boilerplate code (such as change tracking or state management) that
distracts you from the intent of your code logic. When the code is short and focused,
it’s less buggy and easier to grasp.
We can now stop talking theoretically so you can see how to bring reactive pro-
gramming into action in .NET with the help of Rx.
1.2 Introducing Reactive Extensions
Now that we’ve covered reactive programming, it’s time to get to know our star: Reac-
tive Extensions, which is often shortened to Rx. Microsoft developed the Reactive
Extensions library to make it easy to work with streams of events and data. In a way, a
Figure 1.3 The Shoppy application
view of the map. When the user is far
from the Rx shop, the icon is small (on
the left), and as the user gets closer,
the icon gets bigger (on the right).
8 CHAPTER 1 Reactive programming
time-variant value is by itself a stream of events; each value change is a type of event
that you subscribe to and that updates the values that depend on it.
Rx facilitates working with streams of events by abstracting them as observable
sequences, which is also the way Rx represents time-variant values. Observable means
that you as a user can observe the values that the sequence carries, and sequence means
an order exists to what’s carried. Rx was architected by Erik Meijer and Brian Beck-
man and drew its inspiration from the functional programming style. In Rx, a stream
is represented by observables that you can create from .NET events, tasks, or collections,
or can create by yourself from another source. Using Rx, you can query the observ-
ables with LINQ operators and control the concurrency with schedulers;2
that’s why Rx
is often defined in the Rx.NET sources as Rx = Observables + LINQ + Schedulers.3
The
layers of Rx.NET are shown in figure 1.4.
You’ll explore each component of the Rx layers as well as their interactions through-
out this book, but first let’s look at a short history of Rx origins.
1.2.1 Rx history
I believe that to get full control of something (especially technol-
ogy), you should know the history and the details behind the scenes.
Let’s start with the Rx logo which features an electric eel, shown in
figure 1.5; this eel was Microsoft Live Labs’ Volta project logo.
Figure 1.5 The Rx electric eel logo, inspired from the Volta project
2
A scheduler is a unit that holds an internal clock and is used to determine when and where (thread, task, and
even machine) notifications are emitted.
3
Reactive-Extensions/Rx.Net github repository, https://github.com/Reactive-Extensions/Rx.NET.
IObservable<T>
Joins
Projection
Timeout Recovery
Grouping Sampling
Sharing
Aggregating
Filtering
LINQ operators for events
Event streams
Schedulers
Merging Throttling
Windowing
IScheduler
Threads Cloud Dispatchers Time
ISubject<T> IObserver<T>
12
6
1
5
11
7
2
4
10
8
3
9
Figure 1.4 The Rx
layers. In the middle are
the key interfaces that
represent event streams
and on the bottom are
the schedulers that
control the concurrency
of the stream processing.
Above all is the powerful
operators library that
enables you to create an
event-processing
pipeline in LINQ style.
9
Introducing Reactive Extensions
The Volta project was an experimental developer toolset for creating multitier
applications for the cloud, before the term cloud was formally defined. Using Volta,
you could specify which portion of your application needed to run in the cloud
(server) and which on the client (desktop, JavaScript, or Silverlight), and the Volta
compiler would do the hard work for you. Soon it became apparent that a gap existed
in transferring events arising from the server to the clients. Because .NET events aren’t
first-class citizens, they couldn’t be serialized and pushed to the clients, so the observ-
able and observer pair was formed (though it wasn’t called that at the time).
Rx isn’t the only technology that came out of project Volta. An intermediate lan-
guage (IL) to the JavaScript compiler was also invented and is the origin of Microsoft
TypeScript. The same team that worked on Volta is the one that brought Rx to life.
Since its release in 2010, Rx has been a success story that’s been adopted by many
companies. Its success was seen in other communities outside .NET, and it was soon
being ported to other languages and technologies. Netflix, for example, uses Rx
extensively in its service layer and is responsible for the RxJava port.4
Microsoft also
uses Rx internally to run Cortana—the intelligent personal assistant that’s hosted
inside every Windows Phone device; when you create an event, an observable is cre-
ated in the background.
At the time of this writing, Rx is supported in more than 10 languages, including
JavaScript, C++, Python, and Swift. Reactive Extensions is now a collection of open
source projects. You can find information about them as well as documentation and
news at http://reactivex.io/. Reactive Extensions for .NET is hosted under the GitHub
repo at https:/
/github.com/Reactive-Extensions/Rx.NET.
Now that we’ve covered a bit of the history and survived to tell about it, let’s start
exploring the Rx internals.
1.2.2 Rx on the client and server
Rx is a good fit with event-driven applications. This makes sense because events (as
you saw earlier) are the imperative way to create time-variant values. Historically,
event-driven programming was seen mainly in client-side technologies because of the
user interaction that was implemented as events. For example, you may have worked
with OnMouseMove or OnKeyPressed events. For that reason, it’s no wonder that you
see many client applications using Rx. Furthermore, some client frameworks are
based on Rx, such as ReactiveUI (http:/
/reactiveui.net).
But let me assure you that Rx isn’t client-side-only technology. On the contrary,
many scenarios exist for server-side code that Rx will fit perfectly. In addition, as I said
before, Rx is used for large applications such as Microsoft Cortana, Netflix, and com-
plex event processing (CEP) using Microsoft StreamInsight. Rx is an excellent library
for dealing with messages that the application receives, and it doesn’t matter whether
it’s running on a service layer or a client layer.
4
See “Reactive Programming in the Netflix API with RxJava” by Ben Christensen and Jafar Husain (http://
techblog.netflix.com/2013/02/rxjava-netflix-api.html) for details.
10 CHAPTER 1 Reactive programming
1.2.3 Observables
Observables are used to implement time-variant values (which we defined as observable
sequences) in Rx. They represent the push model, in which new data is pushed to (or
notifies) the observers.
Observables are defined as the source of the events (or notifications) or, if you pre-
fer, the publishers of a stream of data. And the push model means that instead of hav-
ing the observers fetch data from the source and always checking whether there’s new
data that wasn’t already taken (the pull model), the data is delivered to the observers
when it’s available.
Observables implement the IObservable<T> interface that has resided in the
System namespace since version 4.0 of the .NET Framework.
public interface IObservable<T>
{
IDisposable Subscribe(IObserver<T> observer);
}
The IObservable<T> interface has only one method, Subscribe, that allows
observers to be subscribed for notifications. The Subscribe method returns an
IDisposable object that represents the subscription and allows the observer to
unsubscribe at any time by calling the Dispose method. Observables hold the collec-
tion of subscribed observers and notify them when there’s something worth notifying.
This is done using the IObserver<T> interface, which also has resided in the System
namespace since version 4.0 of the .NET Framework, as shown here.
public interface IObserver<T>
{
void OnNext(T value);
void OnError(Exception error);
void OnCompleted();
}
The basic flow of using IObservable and IObserver is shown in figure 1.6. Observ-
ables don’t always complete; they can be providers of a potentially unbounded num-
ber of sequenced elements (such as an infinite collection). An observable also can be
“quiet,” meaning it never pushed any element and never will. Observables can also
fail; the failure can occur after the observable has already pushed elements or it can
happen without any element ever being pushed.
This observable algebra is formalized in the following expression (where * indi-
cates zero or more times, ? indicates zero or one time, and | is an OR operator):
OnNext(t)* (OnCompleted() | OnError(e))?
Listing 1.1 The IObservable interface
Listing 1.2 The IObserver interface
Subscribes an observer to
the observable sequence
Notifies the observer of a new
element in the observable sequence
Notifies the
observer that
an exception
has occurred
Notifies the observer that the observable
sequence has completed and no more
notifications will be emitted
Random documents with unrelated
content Scribd suggests to you:
themselves, who are hastening to get out of it—are so intolerable,
that hardly any amount of pay will ever be thought a full recompense
for the sacrifices which a person grown up to man’s estate, and
properly qualified in other respects, would be called upon to make,
were he required to mess in the cock-pit. In the event, therefore, of
such union of offices, the gentleman in whom they are joined ought
to bear a regular commission, mess with the commissioned officers,
and walk the weather side of the deck; perhaps also he might
advantageously wear a suitable uniform. At all events, he ought to
possess a distinct rank, and be considered as essentially a part of
the ship’s complement as the surgeon, purser, or any other officer in
the civil department of the fleet.
People unacquainted with the nature of naval discipline may smile,
perhaps, at some of the privileges glanced at above, as essential to
the right exercise of power. But long experience has shewn that the
distinctions in question are the recognised symbols or indexes of due
subordination and general good order. They unquestionably
contribute, indirectly, to the maintenance of that prompt and effective
obedience, and respect to constituted authority, which, combined
with self-respect, go so far to form the sinews of naval strength. If,
therefore, it be of real utility to have the schoolmaster’s work as well
executed as that of the other officers, it surely follows that he ought
to be placed in a situation to command, not merely the dogged
attention of the midshipmen, but in one which will insure the official
reverence of the boys, together with a proportionate degree of
consideration from those whom they command. If these minute
particulars in balancing the scales of discipline be not duly attended
to, the respect of the pupils will dwindle into familiarity, and the
schoolmaster, if he be not a strong-minded person, may end by
losing his own self-confidence. All lessons then become a farce, and
the teacher either relapses into a useless appendage to the ship, or,
if forcibly sustained by the stern authority of the captain, he is apt to
degenerate into a mere pedagogue.
It may safely be laid down as a pretty general principle, that to
render any man of much use, he must be placed permanently in a
station, which of itself, and by the ordinary workings of the
established order of things, will insure attention both from superiors
and inferiors. Without this adjustment, there can be no good service
performed any where—on land or at sea.
It is sometimes not sufficiently recollected, that schooling on board
ship differs materially from what it is on shore; for it not only treats of
very different matters, but has other objects in view, both immediate
and remote. Before a young person actually engages in a
profession, the great purpose of a school appears to consist in mere
training—that is to say, in carrying his faculties through a course of
preparatory discipline, without any more specific object than mental
exercise. But when the youth is once fairly embarked in the pursuit
which is to furnish employment for his life, an immediate modification
takes place. The system which it is necessary to follow at sea is then
placed in distinct contrast to that previously observed.
On shore, education and business are two separate things, one of
which does not begin till the other ends; while, on board ship, the two
always go hand in hand. As the lessons of the teacher may be put in
practice immediately, the utility of theoretical knowledge is exhibited
on the spot; and thus a gradually increasing impulse is given to the
whole course of study. A boy who learns from his master what the
word Latitude means, and what is the method of obtaining it,
instantly runs upon deck, takes a quadrant in his hand, observes the
sun’s meridional altitude, and is filled with amaze and delight on
discovering: within what small limits he has been able to determine
the ship’s place relatively to the equator. Next day he sets to work
with increased eagerness to conquer the more difficult problem of
finding the Longitude, which he has immediate opportunities of
bringing to the test of actual experiment. The theory of Gunnery,
likewise, when studied by itself, is frequently found to be intricate,
and often far from satisfactory; but, when all its results can be
brought to the test of experiment, the aspect which this very
important pursuit assumes is totally different. How few officers, for
instance, understand correctly the meaning of the elementary term
Point Blank, or have any useful conception of the mathematical
principles which it involves! How often do we hear people gravely
assuming that the shot rises between the gun and the point-blank
mark! The laws which regulate the action of fluids directed against
plane surfaces are by no means easily explained when grappled with
alone; but, when brought to bear on the use of the rudder, or the trim
of the sails, there is hardly a boy afloat who fails to appreciate the
value of true science over what is called ‘rule of thumb;’ or rather,
who may not soon be taught to feel the mighty advantage of uniting
the two, so as to make theory and practice mutually assist each
other.
Nearly the same thing may be said of almost every other branch of
knowledge: with languages, for instance—I mean more particularly
the modern languages—French, Spanish, Portuguese, and Italian,
most of which are made to tell generally as soon as acquired. The
Mathematics in all their wonderful branches, and Science in almost
every department, furnish ample objects to fill up the leisure hours of
an officer. Geography, history, and the law of nations, come into
professional play at every turn. A young man, therefore, of any
capacity or industry, is nearly sure of rendering himself useful in a
short time, be his particular pursuits what they may, provided only
that his zeal is duly encouraged by the captain, and seconded by the
ready assistance of a properly qualified preceptor whom he has
been taught to respect. It must never be forgotten, however, that
along with all this knowledge of a professional, literary, or scientific
nature, there ought to be mixed up instructions of a still more
important description, upon which the formation of a young man’s
character will mainly depend, whether we view him merely as an
officer, or in his wider capacity as a member of the civil community.
Every one acquainted with the difficult task of bringing boys safely
through the intricate labyrinth of temptations which must be
encountered in the early stages of a sea life, will acknowledge, that
the superintendent of a young man’s habits has little or no chance of
success, unless he can secure the confidence of his pupil. I very
much fear, however, that there can be little hope of establishing such
a relation between them, unless the preceptor be truly the superior,
not only in station but in attainments, and unless it be his peculiar
study to acquire this ascendency over his pupil’s mind, in order to
the better regulation of his manners. I use the word manners in its
largest sense; and it is clear that, unless the schoolmaster have
leisure to keep these objects constantly in view, he cannot hope to
gain the proper degree of influence over any boy’s mind. As chaplain
of the ship, however, his religious duties, so far from interfering with
the objects alluded to, would blend admirably with all of them, and
furnish the best means, and, if it were needed, the best excuse, for a
judicious and parental sort of interference. To expect that any such
interference of the schoolmaster, under the present system, can be
efficacious, is, I much fear, a complete delusion; and this furnishes a
strong reason for uniting in one person the kindred duties of chaplain
and teacher. It shews, at the same time, how inefficient any such
union must be, unless care be taken to secure fitting persons to fill a
joint office of such delicacy.
There is still another, and by no means an unimportant benefit,
which might arise to the naval service from this improvement: I mean
its effect on the higher classes of officers. If there be nothing more
shocking than a disreputable clergyman in a mess-room, so, on the
other hand, I conceive there can be nothing more useful, in many
very material respects, than the constant companionship of a right-
minded and well-educated person of this description. I say nothing of
the obvious and salutary influence which his presence never fails to
exercise over the manners of men, already too much disposed to
laxity in their habits; but it may be well to consider, likewise, the great
additional benefits which may arise to the officers from their
possessing the means of instructing themselves in the different
branches of knowledge, with which a chaplain, regularly qualified to
teach, would be able to impart.
Except on board ship, and at sea, few of the senior officers of the
Navy, in war time, have the opportunity, and still fewer the means, of
improving their acquaintance with those pursuits, of which, in the
earlier periods of their service, they may have gained a smattering. I
allude to the classics, to modern languages, and the belles lettres
generally, to the higher branches of mathematics, and to many of
those sciences formerly deemed abstruse, but which have lately
become popular; such as chemistry, geology, and natural history in
all its departments.
The time is not remote when it was held by high naval authorities,
that all or any of these refinements, instead of being useful to an
officer, actually stood in his way; and, as far as they went, interfered
with the due execution of his duty. Nor can it, or ought it, to be
denied, that the principle of extra instruction is very apt to be carried
too far, and the refining system overdone. Nor must it ever be
forgotten in these discussions, that the service—that is to say, the
hard, regular, seamanlike round of official duties, in all seasons, and
under all circumstances, ought always to be the primary objects of
an officer’s thoughts, before which every thing else is not only to
bend, but, if need be, must break. And it is chiefly on the principle of
rendering an officer only the more fit for such technical routine, that
any of the pursuits alluded to can ever be considered as having
legitimate claims on his attention. If such studies become so
engrossing as to detach his thoughts from his sterner duty; to make
him a scholar instead of a seaman, a dandy instead of a
disciplinarian; or if he allow himself to attend to these extraneous
matters with any other view than to his improvement as a strictly
professional man, he will, of course, find them, one and all,
prejudicial, and not be encouraged. Under proper regulation,
however, there seems little or no danger of any thing of this
description proving injurious to an officer’s character, as a useful,
hard-working servant of the public.
It was formerly thought, that high-born, high-bred, and even well-
educated men, were less fitted to make good officers for the ordinary
course of professional work, than persons who had sprung from a
lower origin, or whose education was limited to the mere
technicalities of the profession, and who were without taste and
without manners—men of the Hawser Trunion school, in short. But
the copious experience of the late arduous war seems to have
shewn, both in the army and in the navy, that the contrary is the true
state of the case. And certainly, as far as my own observation and
inquiries have gone, I have found reason to believe that those
officers who are the best informed and the best bred, and who
possess most of the true spirit of gentlemen, are not only the safest
to trust in command over others, but are always the readiest to yield
that prompt and cheerful obedience to their superiors, which is the
mainspring of good order. Such men respect themselves so justly,
and value their own true dignity of character so much, and are at all
times so sensitively alive to the humiliation of incurring reproach, that
they are extremely cautious how they expose themselves to merited
censure. From the early and constant exercise of genuine
politeness, they become habitually considerate of the feelings of
others; and thus, by the combined action of these great principles of
manners, officers of this stamp contrive to get through much more
work, and generally do it much better, than persons of less
refinement. Moreover, they consider nothing beneath their closest
attention which falls within the limits of their duty; and, as a leading
part of this principle, they are the most patient as well as vigilant
superintendents of the labours of those placed under their authority,
of any men I have ever seen. It is not that they watch their inferiors
with a view to entrap and pounce upon them, but solely with the
public-spirited and generous object of keeping all parties right, in
order, by checking errors in the outset, before they have grown into
crimes, to prevent the hard necessity of punishment.
This is a pretty fair sketch of the method of acting observed by a
thorough-bred, gentlemanlike, well-instructed officer; and every one
who has been in command, and in protracted difficulties, or has
merely been employed in the ordinary course of service, will readily
admit that, with the assistance of such men, every department of his
duty has gone on better and more pleasantly than it could have
possibly done if the persons under his command had been of a
coarser stamp.
It is quite true that the full degree of refinement alluded to can
hardly ever be fully taught on board ship. But it may often be
approximated to good purpose. It is quite within our power, for
example, so to train up young men, that they shall gradually acquire
not only that sort of knowledge, but also those habits, which
experience has shewn to have the most direct tendency to enlarge
the understanding, and to chastise the taste. Precisely as this
amount of intelligence increases, so will the capacity of an officer to
do good service increase likewise; and it is absurd to suppose that
he will be less disposed to do his duty well, from knowing better how
to comply with its obligations.
Weak minds and perverse dispositions, under any system of
instruction or of discipline, will, of course, defeat these calculations;
and there will, therefore, always be many effeminate and idle
persons in a fleet, who, by mistaking mere acquirements for the
knowledge of how to turn them to useful account, deserve the title
they receive of ‘the King’s hard bargains.’ But, taking the average
run of officers in the Navy, it may safely be expected, that if, in other
respects, they are kept to their duty, and if they themselves have a
real interest in the service, the more information they can acquire
upon every subject worthy of a gentleman’s attention, the better will
they be fitted for the performance not only of those higher exploits
which all the world understand and admire, but even of those humble
and unseen professional avocations, which make up by far the
greater and the most important part of our daily duties.
If, then, we can furnish all ranks of our naval officers afloat with a
ready and agreeable means of filling up their time, of which most of
them have a good deal to spare, we may fairly hope that they will not
be slow to avail themselves of the opportunities placed within their
reach. In order, however, to render these measures of any extensive
utility, this plan of furnishing assistance must be carried a long way.
A chaplain-schoolmaster should be allowed even to the smallest
class of ships on board which, by any contrivance, the proper degree
of accommodation can be obtained. And if these ideas were followed
up in the admirable spirit with which some recent improvements
have been carried into effect in the Navy, for instance, in the
discipline, victualling, payment of wages, ratings, and other matters,
a very great boon would be conferred on the service.
It is not likely that the measure proposed would materially
augment the expenses of the Navy, if, indeed, it had that effect at all;
since both a chaplain and schoolmaster are expressly allowed to all
ships, from the first to the sixth class, inclusive. But, even supposing
the expense were to be augmented, there can be no doubt, I should
conceive, in the mind of any person who has reflected seriously on
these subjects, that the return for such outlay would be speedy and
certain. The religious, moral, and intellectual character of officers, on
whose good conduct so much depends, must, in every conceivable
state of things, be an object of material consequence to the country.
And it were really almost a libel on the nation, to imagine that they
would not cheerfully agree to the additional expenditure which might
be required, if the advantages be such as are stated. There can be
no truer economy, than expending money for the promotion of virtue
and sound knowledge amongst this class of public servants. For
their duties, it must be recollected, generally lie so far beyond the
reach of ordinary scrutiny, that almost the only security we have for
their good conduct rests on their own sense of honour. A dishonest
officer on a foreign station might often divert from its proper purpose,
by a single stroke of his pen, and without much danger of detection,
more of the public money than would furnish the Navy with chaplains
and schoolmasters for ten years.
It is to accomplish only one-half the great task of instruction merely
to fill a boy’s head with technical information—his principles and
habits ought to be likewise taken into our safe keeping. It is also
greatly to be desired, that, when the period arrives at which he is
expected to become, as it is called, his own master, he should find
no difficulty in continuing, from choice, those pursuits to which he
had previously applied himself on compulsion, or merely as a means
of promotion. And there seems to be no method more likely to
accomplish this desirable purpose, than affording the young
commissioned officer the companionship of an instructor, or, at all
events, of a person whose duty it should be, if required, not only to
continue, in the ward-room, the course of information commenced in
the cock-pit, but whose aim ought to be, so to modify these studies
as to adapt them to the altered circumstances of the pupil, and to win
his attention to their pursuit by rendering them agreeable and useful.
It is not pretended, by any means, that such a task is an easy one;
on the contrary, it will require not only considerable abilities, but high
attainments, and no inconsiderable degree of good taste, together
with a long apprenticeship of self-discipline, and an exclusive
application to these arduous duties, as the grand object and
business of the instructor’s life.
There really appears, however, to be no situation but that of a
clergyman which offers any reasonable chance of these conditions
being fulfilled. And as the education of such a person is necessarily
expensive, and the double office which it is proposed he should fill,
one of great responsibility, labour, and difficulty, as well as one of
peculiar and irremediable discomfort and privation, without any of
those energetic excitements which stimulate every other class of
officers to exertion, the remuneration ought clearly to be very
considerable, otherwise no set of properly qualified men will engage
permanently in its pursuit.
A distinct class of officers, of this sacred character, although as yet
they do not exist, might be readily created. If the emoluments of the
chaplain of a man-of-war were respectable, the situation rendered as
agreeable, in point of comfort, as the nature of the elements will
admit of, and if the prospects of future provision be made certain, or
contingent only upon a right performance of duty, there cannot, I
think, be a doubt that, in a short time, there would be an ample and
steady supply of chaplains, as highly qualified, in point of
attainments, as the Admiralty might choose to fix on the scale.
If this important professional object were once fairly carried into
effect, we should probably soon discover an improvement in the
whole system of naval discipline, the best evidences of which would
be, the increased efficiency of the whole service, arising out of the
gradually ameliorated habits and higher intellectual cultivation, as
well as improved tastes and more rational happiness, of every class
of the officers, from the oldest captain down to the youngest first-
class boy, just untied from his mother’s apron-string.
In all that has been said, I have taken into view almost exclusively
the advantages which would accrue to the officers from the adoption
of this plan of uniform instruction. It is to them, individually as
gentlemen, and collectively as a body, upon the certainty of whose
hearty exertions the government can at all times depend, that the
country must ever look for that energetic momentum in our naval
strength, upon which the national power, in this department,
essentially rests. Surely, however, it is not too much to say, as a
matter of experience, that the influence of a resident clergyman on
board ship, wherever there is one, over the minds of the crew, is felt
to be quite as salutary, when properly exercised, as it is to the
labourers in any parish of the empire.
It signifies nothing to say that the structure of naval discipline is
widely different from the civil administration of the land; for the very
same principles, and, more or less, the very same motives to right or
wrong action, must always be in play in both cases. A judicious
chaplain, therefore, who shall have become acquainted by personal
experience with the habits, tastes, feelings, and pursuits of the
seamen, may undoubtedly contribute an important share to the
efficiency of the whole of our naval system. So far from interfering
with, or in any way checking the strict course of nautical affairs, I
conceive that the chaplain’s influence, rightly exercised, acting in
cordial understanding with the captain, and sanctioned by his
authority, might advance the best interests of the service by greatly
diminishing offences, and thus lessening the melancholy necessity of
punishments. Whenever this benevolent purpose can be effected, in
a greater or less degree, both those who obey and those who
command are sure to be better pleased with one another, and, it is
reasonable to suppose, far more desirous of co-operating heartily in
the accomplishment of the common purpose for which they are
brought together.
END OF THE FIRST VOLUME.
LONDON:
J. MOYES, TOOK’S COURT, CHANCERY LANE.
FOOTNOTES:
[2] I quote from a paper on the State of Education in the British
Navy, printed in the United Service Journal, Part XI. for October
1830. The performance and the promise of the very rising officer,
who wrote this article, help to furnish the fairest practical answer
to those who object to the early advancement of young men of
rank in the Navy.
Transcriber’s Notes
pg 219 Changed: when on board passage vesssels
to: when on board passage vessels
pg 225 Changed: half of sound snoose
to: half of sound snooze
pg 308 Changed: as the captian can ameliorate the habits
to: as the captain can ameliorate the habits
*** END OF THE PROJECT GUTENBERG EBOOK FRAGMENTS
OF VOYAGES AND TRAVELS, INCLUDING ANECDOTES OF A
NAVAL LIFE ***
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

More Related Content

PDF
Buy ebook Rx.NET in Action with Examples in C# 1st Edition Tamir Dresher chea...
PDF
Rxjs In Action Covers Rxjs 5 1st Edition Paul P Daniels Luis Atencio
PDF
JavaScript Application Design A Build First Approach 1st Edition Nicolas Beva...
PDF
Vertx In Action Asynchronous And Reactive Java Julien Ponge
PDF
Akka in Action 1st Edition Raymond Roestenburg download pdf
PDF
Data Pipelines with Apache Airflow 1st Edition Bas P Harenslak Julian Rutger ...
PDF
JavaScript Application Design A Build First Approach 1st Edition Nicolas Beva...
PDF
[PDF Download] Akka in Action 1st Edition Raymond Roestenburg fulll chapter
Buy ebook Rx.NET in Action with Examples in C# 1st Edition Tamir Dresher chea...
Rxjs In Action Covers Rxjs 5 1st Edition Paul P Daniels Luis Atencio
JavaScript Application Design A Build First Approach 1st Edition Nicolas Beva...
Vertx In Action Asynchronous And Reactive Java Julien Ponge
Akka in Action 1st Edition Raymond Roestenburg download pdf
Data Pipelines with Apache Airflow 1st Edition Bas P Harenslak Julian Rutger ...
JavaScript Application Design A Build First Approach 1st Edition Nicolas Beva...
[PDF Download] Akka in Action 1st Edition Raymond Roestenburg fulll chapter

Similar to Full Download Rx.NET in Action with Examples in C# 1st Edition Tamir Dresher PDF DOCX (20)

PDF
ASP NET MVC in Action 1st Edition Jeffrey Palermo
PDF
ASP NET MVC in Action 1st Edition Jeffrey Palermo
PDF
Complete-NGINX-Cookbook-2019.pdf
PDF
Kubernetes in Action First Edition Marko Luksa
PDF
Openstack In Action 1st Edition V K Cody Bumgardner
PDF
WebWork in Action In Action First Edition Patrick Lightbody
PDF
ASP.NET Core in Action (2018).pdf
PDF
Struts 2 In Action 1st Edition Don Brown Chad Michael Davis Scott Stanlick
PDF
WebWork in Action In Action First Edition Patrick Lightbody
PDF
Kubernetes in Action First Edition Marko Luksa
PDF
Kubernetes in Action First Edition Marko Luksa
PDF
ASP NET 4 0 in Practice Daniele Bochicchio
PDF
WebWork in Action In Action First Edition Patrick Lightbody
PDF
Download full ebook of Java Cookbook Ian F Darwin Darwin Ian F instant downlo...
PDF
Testing Microservices With Mountebank 1st Edition Brandon Byars
PDF
Getting MEAN with Mongo Express Angular and Node 1st Edition Simon Holmes
PDF
ASP NET 4 0 in Practice Daniele Bochicchio
PDF
Getting MEAN with Mongo Express Angular and Node 1st Edition Simon Holmes
PDF
Download full ebook of Azure in Action 1st Edition Chris Hay instant download...
PDF
AOP in NET Practical Aspect Oriented Programming Matthew D. Groves
ASP NET MVC in Action 1st Edition Jeffrey Palermo
ASP NET MVC in Action 1st Edition Jeffrey Palermo
Complete-NGINX-Cookbook-2019.pdf
Kubernetes in Action First Edition Marko Luksa
Openstack In Action 1st Edition V K Cody Bumgardner
WebWork in Action In Action First Edition Patrick Lightbody
ASP.NET Core in Action (2018).pdf
Struts 2 In Action 1st Edition Don Brown Chad Michael Davis Scott Stanlick
WebWork in Action In Action First Edition Patrick Lightbody
Kubernetes in Action First Edition Marko Luksa
Kubernetes in Action First Edition Marko Luksa
ASP NET 4 0 in Practice Daniele Bochicchio
WebWork in Action In Action First Edition Patrick Lightbody
Download full ebook of Java Cookbook Ian F Darwin Darwin Ian F instant downlo...
Testing Microservices With Mountebank 1st Edition Brandon Byars
Getting MEAN with Mongo Express Angular and Node 1st Edition Simon Holmes
ASP NET 4 0 in Practice Daniele Bochicchio
Getting MEAN with Mongo Express Angular and Node 1st Edition Simon Holmes
Download full ebook of Azure in Action 1st Edition Chris Hay instant download...
AOP in NET Practical Aspect Oriented Programming Matthew D. Groves
Ad

Recently uploaded (20)

PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Lesson notes of climatology university.
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
Institutional Correction lecture only . . .
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Complications of Minimal Access Surgery at WLH
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Pharma ospi slides which help in ospi learning
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
master seminar digital applications in india
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Sports Quiz easy sports quiz sports quiz
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPH.pptx obstetrics and gynecology in nursing
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Pharmacology of Heart Failure /Pharmacotherapy of CHF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Microbial disease of the cardiovascular and lymphatic systems
Lesson notes of climatology university.
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Institutional Correction lecture only . . .
Final Presentation General Medicine 03-08-2024.pptx
Complications of Minimal Access Surgery at WLH
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Pharma ospi slides which help in ospi learning
O7-L3 Supply Chain Operations - ICLT Program
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Supply Chain Operations Speaking Notes -ICLT Program
master seminar digital applications in india
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Sports Quiz easy sports quiz sports quiz
Ad

Full Download Rx.NET in Action with Examples in C# 1st Edition Tamir Dresher PDF DOCX

  • 1. Download the full version of the textbook now at textbookfull.com Rx.NET in Action with Examples in C# 1st Edition Tamir Dresher https://textbookfull.com/product/rx-net-in-action- with-examples-in-c-1st-edition-tamir-dresher/ Explore and download more textbook at https://textbookfull.com
  • 2. Recommended digital products (PDF, EPUB, MOBI) that you can download immediately if you are interested. C++20 in Examples. 1st Edition Alex Vasilev https://textbookfull.com/product/c20-in-examples-1st-edition-alex- vasilev/ textbookfull.com Spark in Action - Second Edition: Covers Apache Spark 3 with Examples in Java, Python, and Scala Jean-Georges Perrin https://textbookfull.com/product/spark-in-action-second-edition- covers-apache-spark-3-with-examples-in-java-python-and-scala-jean- georges-perrin/ textbookfull.com R in Action Data Analysis and Graphics with R Bonus ch 23 ONLY 2nd Edition Robert Kabacoff https://textbookfull.com/product/r-in-action-data-analysis-and- graphics-with-r-bonus-ch-23-only-2nd-edition-robert-kabacoff/ textbookfull.com Advances in Transitional Flow Modeling Applications to Helicopter Rotors 1st Edition Chunhua Sheng (Auth.) https://textbookfull.com/product/advances-in-transitional-flow- modeling-applications-to-helicopter-rotors-1st-edition-chunhua-sheng- auth/ textbookfull.com
  • 3. Nephrology Worldwide 1st Edition José A. Moura-Neto (Editor) https://textbookfull.com/product/nephrology-worldwide-1st-edition- jose-a-moura-neto-editor/ textbookfull.com An Introduction to Management Science: Quantitative Approach David R. Anderson & Dennis J. Sweeney & Thomas A. Williams & Jeffrey D. Camm & James J. Cochran https://textbookfull.com/product/an-introduction-to-management- science-quantitative-approach-david-r-anderson-dennis-j-sweeney- thomas-a-williams-jeffrey-d-camm-james-j-cochran/ textbookfull.com Cultural Anthropology: Appreciating Cultural Diversity Conrad Phillip Kottak https://textbookfull.com/product/cultural-anthropology-appreciating- cultural-diversity-conrad-phillip-kottak/ textbookfull.com Practical Business Negotiation 2nd Edition William W. Baber (Author) https://textbookfull.com/product/practical-business-negotiation-2nd- edition-william-w-baber-author/ textbookfull.com Dental Radiography Principles and Techniques Iannucci Dds Ms https://textbookfull.com/product/dental-radiography-principles-and- techniques-iannucci-dds-ms/ textbookfull.com
  • 4. Topological Vector Spaces and Their Applications 1st Edition V.I. Bogachev https://textbookfull.com/product/topological-vector-spaces-and-their- applications-1st-edition-v-i-bogachev/ textbookfull.com
  • 5. Rx.NET in Action TAMIR DRESHER M A N N I N G SHELTER ISLAND
  • 6. ISBN 9781617293061 Printed in the United States of America ©2017 by Manning Publications Co.
  • 7. contents foreword xi preface xiii acknowledgments xv about this book xvii about the author xxi about the cover illustration xxii PART 1 GETTING STARTED WITH REACTIVE EXTENSIONS .................................................... 1 1 Reactive programming 3 1.1 Being reactive 4 Reactiveness in your application 6 1.2 Introducing Reactive Extensions 7 Rx history 8 ■ Rx on the client and server 9 Observables 10 ■ Operators 12 ■ The composable nature of Rx operators 13 ■ Marble diagrams 14 Pull model vs. push model 15 1.3 Working with reactive systems and the Reactive Manifesto 17 Responsiveness 17 ■ Resiliency 18 ■ Elasticity 18 Message driven 19 ■ Where is Rx? 20
  • 8. 1.4 Understanding asynchronicity 20 It’s all about resource use 21 ■ Asynchronicity and Rx 23 1.5 Understanding events and streams 24 Everything is a stream 24 1.6 Summary 26 2 Hello, Rx 27 2.1 Working with traditional .NET events 28 Dealing with concurrency 33 ■ Retrospective on the solution and looking at the future 35 2.2 Creating your first Rx application 39 Selecting Rx packages 39 ■ Installing from NuGet 42 2.3 Writing the event-processing flow 44 Subscribing to the event 44 ■ Grouping stocks by symbol 45 Finding the difference between ticks 46 ■ Cleaning resources 49 ■ Dealing with concurrency 50 Wrapping up 50 2.4 Summary 52 3 Functional thinking in C# 54 3.1 The advantages of thinking functionally 55 Declarative programming style 55 ■ Immutability and side effects 56 ■ First-class functions 58 ■ Being concise 59 3.2 First-class and higher-order functions using delegates and lambdas 59 Delegates 60 ■ Anonymous methods 61 ■ Lambda expressions 63 ■ Func and Action 64 ■ Using it all together 66 3.3 Method chaining with extension methods 70 Extending type behavior with extension methods 70 Fluent interfaces and method chaining 72 ■ Creating a language 74 3.4 Querying collections with LINQ 75 What does LINQ look like? 77 ■ Nested queries and joins 78 Anonymous types 79 ■ LINQ operators 81 ■ Efficiency by deferred execution 83 3.5 Summary 86
  • 9. PART 2 CORE IDEAS ................................................... 87 4 Creating observable sequences 89 4.1 Creating streams of data and events with observables 90 Implementing the IObservable<T> interface 90 ■ The problem with handcrafted observables 93 ■ The ObservableBase 93 Creating observables with Observable.Create 96 ■ Deferring the observable creation 97 4.2 Creating observables from events 99 Creating observables that conform to the EventPattern 99 Events that aren’t following the event pattern 102 Events with multiple parameters 102 ■ Dealing with events that have no arguments 104 4.3 From enumerables to observables and back 104 Enumerable to observable 105 ■ Observable to enumerable 107 4.4 Using Rx creational operators 110 Generating an observable loop 110 ■ Reading a file 111 The primitive observables 112 4.5 Summary 113 5 Creating observables from .NET asynchronous types 115 5.1 Bridging .NET asynchronous types with Rx 116 Changing the synchronous method to asynchronous 117 Creating the primes observable 117 ■ Using async-await in observable creation 121 ■ Converting tasks to observables 122 Running asynchronous code as part of the pipeline 124 Controlling the results order 128 5.2 Creating observables of periodic behavior 130 Emitting values in time intervals 130 ■ Creating an observable timer 131 ■ Scheduling an emission with a timer 132 5.3 Summary 134 6 Controlling the observer-observable relationship 135 6.1 Creating observers 136 The observable-observer communication 136 ■ Creating observers without leaving the pipeline 137 ■ Not passing OnError and asynchronous observables 139 ■ Replacing the subscription disposal with cancellation 140 ■ Creating an observer instance 141
  • 10. 6.2 Controlling the observable-observer relationship lifetime 142 Delaying subscription 143 ■ Stop emitting notifications at a scheduled time 145 ■ Discarding items when another observable emits 145 ■ Skipping notifications 147 ■ Taking or stopping when a condition is met 148 ■ Resubscribing 150 ■ Adding side effects in the observable pipeline 151 6.3 Putting it all together 153 6.4 Summary 155 7 Controlling the observable temperature 157 7.1 Multicasting with subjects 158 Simple broadcasting with Subject<T> 160 ■ Representing asynchronous computation with AsyncSubject 163 Preserving the latest state with BehaviorSubject 165 Caching the sequence with ReplaySubject 166 ■ Hiding your subjects 167 ■ Following best practices and guidelines 169 7.2 Introducing temperature: cold and hot observables 169 Explaining cold and hot observables 170 ■ Cold observable 171 Hot observables 171 7.3 Heating and cooling an observable 171 Turning cold into hot 171 ■ Using ConnectableObservable 174 Publishing and multicasting 175 ■ Using Multicast 178 Managing the ConnectableObservable connection 179 Cooling a hot observable to allow replaying 181 7.4 Summary 183 8 Working with basic query operators 184 8.1 Selecting what’s important (mapping) 185 8.2 Flattening observables 187 Flattening observables of enumerables 187 ■ Flattening observables of observables 190 8.3 Filtering an observable 192 Filtering with the Where operator 192 ■ Creating a distinct sequence 193 ■ Removing duplicate contiguous values 195 8.4 Aggregating the observable sequence 196 Using basic aggregation operators 196 ■ Finding the maximum and minimum items by condition 200 ■ Writing your aggregation logic with Aggregate and Scan 201 8.5 Summary 203
  • 11. 9 Partitioning and combining observables 205 9.1 Combining observables 206 Pairing items from observables (zipping) 206 ■ Combining the latest emitted values 207 ■ Concatenating observables 208 ■ Merging observables 209 ■ Dynamic concatenating and merging 210 ■ Switching to the next observable 212 9.2 Grouping elements from the observable 214 9.3 Joining observables (coincidence-based combining) 215 Joining to a flat stream 215 ■ Joining into groups 219 9.4 Buffers and sliding windows 221 Buffering 222 ■ Windowing the observable sequence 226 9.5 Summary 229 10 Working with Rx concurrency and synchronization 231 10.1 Controlling concurrency with schedulers 231 Defining the scheduler 232 ■ Parameterizing concurrency 235 Types of schedulers 237 10.2 Using time-based operators 241 Adding a timestamp to a notification 242 ■ Adding the time interval between notifications 243 ■ Adding a time-out policy 244 ■ Delaying the notifications 245 ■ Throttling the notifications 247 ■ Sampling the observable in intervals 249 10.3 Synchronizing the observable emissions 250 Changing the observation’s execution context 250 ■ Changing the subscription/unsubscription execution context 251 ■ Using SubscribeOn and ObserveOn together 253 ■ Synchronizing notifications 255 10.4 Summary 257 11 Error handling and recovery 259 11.1 Reacting to errors 260 Errors from the observable side 260 ■ Catching errors 262 Retrying to subscribe in case of an error 264 11.2 Controlling the lifetime of resources 265 Disposing in a deterministic way 266 ■ Deterministic finalization 269 ■ Dangling observers 270
  • 12. 11.3 Dealing with backpressure 276 Observables of different rates 276 ■ Mitigating backpressure 278 11.4 Summary 279 appendix A Writing asynchronous code in .NET 281 appendix B The Rx Disposables library 291 appendix C Testing Rx queries and operators 298 index 313
  • 13. foreword This book, Rx.NET in Action, does a great job in explaining the details and back- ground that .NET developers need to effectively use Rx. In particular, it explains how to connect the plethora of asynchronous types in .NET to Rx observables, and how to deal with errors, resource allocation, and last but not least, concurrency. Since its inception, the .NET Framework has emphasized the importance of asyn- chronous execution and nonblocking I/O. Through delegates, the .NET Framework has emphasized higher-order functional programming from the beginning, and by automatically defining the BeginInvoke and EndInvoke methods on delegates, devel- opers may call any method asynchronously. But the BeginInvoke/EndInvoke pattern for asynchronous operations is tedious and verbose, because it requires converting your code into continuation-passing style. As an alternative, the .NET Framework introduced the event-based asynchronous pat- tern that uses the built-in support of .NET for events and event handlers. Although the event-based pattern was a big step forward compared to asynchronous delegates, more opportunities remained to streamline the development experience. For synchronous streams of values, modeled by the standard interfaces of Enumer- able/IEnumerator, the LINQ standard query operators provide a beautiful and ele- gant algebra for processing streams in a high-level and declarative manner. Wouldn’t it be nice if we could use the fact that events are conceptually also streams of values and hence provide a similar LINQ-based programming model for events? Another disadvantage of using events for asynchronous calls is that this ignores the fact that unlike most other events, such as mouse clicks, the events wired up to asyn- chronous operations produce at most one value. Wouldn’t it be nice if we could use the fact that asynchronous methods return only a single value and hence provide a
  • 14. similar imperative programming model that supports regular control-flow-like condi- tionals, loops, and exception handling for asynchronous methods? As it turns out, the answer to both questions is a resounding yes! By using the mathematical trick of equalization, we can mechanically convert the IEnumerable /IEnumerator interfaces for synchronous pull-based streams into the monadic IObservable/IObserver interfaces for asynchronous push-based streams. The async/await syntax in C# and Visual Basic allows developers to use regular imperative syntax to write both synchronous and asynchronous methods, and the LINQ query comprehensions allow developers to write queries over both synchronous and asyn- chronous data streams This is the heart of Rx. Many languages outside the .NET world have now adopted the magic square of one/many × sync/async, making developers happy and produc- tive no matter what language they’re using. If you’re a .NET developer, you’ll want to keep a copy of this book handy to put Rx.NET into action! —ERIK MEIJER INVENTOR OF RX, FOUNDER OF APPLIED DUALITY
  • 15. Visit https://textbookfull.com now to explore a rich collection of eBooks, textbook and enjoy exciting offers!
  • 16. preface Reactive Extensions (Rx) for .NET was first published in November 2009 under the short description “Rx is a .NET Library that allows programmers to write succinct declarative code to orchestrate and coordinate asynchronous and event-based pro- grams based on familiar .NET idioms and patterns.” (See http://mng.bz/gQ31.) I remember watching the first examples and reading the discussions. I was amazed by the elegance of the solutions and how simple they looked. Unfortunately, when I sat down and tried to use Rx, things were harder than I thought, and the mental change I needed to make toward reactive programming was significant. In those days, there wasn’t a lot of material on the subject, and I had to struggle to solve my issues and learn things the hard way with a lot of trial and error. In 2012, at end of my military service and upon joining CodeValue (www.code- value.net), I had two major projects that enabled me to really appreciate my Rx knowl- edge. The first was about a cybersecurity application that needed to react to multiple events and coordinate them in order to show the end user the state of various inci- dents all happening in parallel. The second was a video chat application, running on mobile and PC devices. The video chat application reacted to events such as users log- ging in and out of the system and receiving messages of various types that had to be dealt with differently. Though these two systems were different, they shared the same problems of writing a flow based on events—a flow that involves filtering of received values, dealing with asynchronicity and concurrency, and identifying patterns of recur- ring events so that the application could respond efficiently and correctly. I intro- duced Rx to both of those systems, and it was one of the things that made each a success. We exceeded expectations and preceded our schedule. Still, even though I had knowledge of Rx, problems still happened from time to time, and little material on Rx, such as books and guides, was available. Many times
  • 17. problems originated because of my colleagues’ lack of knowledge or situations that were new to us. Luckily, after I identified the problem source, it would be easy to fix, mostly because of the flexibility of Rx operators. In the following years, I started to blog and speak about Rx and how it made solving complex problems easy. That is when the idea for this book started to grow. My vision was to create a step-by-step guide that holds the pieces needed for the .NET programmer to get the maximum out of the Rx library and the reactive programming paradigm. I also wanted to write about the practices that I acquired over the years, as well as the pitfalls and their solutions. It took hard and careful work to make sure the book fulfills its aim. Some chapters had to be rewritten, topics were changed, and some material had to be left out in order to concentrate on the important and fundamental features. The result of this hard work is Rx.NET in Action, a book that you can read front to back or go directly to a specific chapter to solve a problem or refresh your memory. Rx is an evolving technology that was also ported to numerous other platforms and languages. It is an open source project and part of the .NET Foundation (www.dotnet- foundation.org). My hope is that Rx will become the de facto way to program, orches- trate, and coordinate asynchronous and event-based programs in .NET and that this book will give you everything you need to be ready for this new and exciting world of Rx.
  • 18. about this book Rx.NET in Action is a full guide for the Reactive Extensions library for .NET developers. It delivers explanations, best practices, and tips and tricks that will allow you to fully use Rx in your applications. Who should read this book Rx.NET in Action is for .NET developers who write event-based and asynchronous applications and need powerful consuming and querying capabilities over events and push-based sources. Rx.NET in Action is also suitable for developers who are curious about reactive pro- gramming and the Rx library techniques, but who may not have an immediate need to use it. Adding Rx know-how to your toolbox is valuable for future projects; reactive programing is a hot topic and will continue to be in the future. This book primarily uses the .NET version of Rx, and the code examples use the C# language. Readers familiar with C# will be right at home. This book is suitable for any platform supported by .NET (including .NET Core). How this book is organized The book’s 11 chapters are divided into two sections. Part 1 provides an introduction to reactive programming and to the .NET skills you need in order to understand the functional aspects of the library.  Chapter 1 explores the reactive programming paradigm and Reactive Mani- festo concepts. The chapter introduces the building blocks of Rx and explains when and why it should be used.
  • 19.  Chapter 2 is where you really meet Rx and the steps needed to incorporate it into your application. It shows a simple case-study of using Rx inside an application and compares two versions of the same application, before and after Rx is used.  Chapter 3 provides an overview of the functional programming concepts and techniques that Rx uses and how they’re provided with the .NET Framework and the C# language. Part 2 dives into each of the tasks you’ll do with Rx—from creating observables and observers, to controlling their lifetimes and reacting to queries you create on top of them.  Chapter 4 teaches ways to create observable sequences and it shows how syn- chronous observables can be created from enumerables and built-in creation operators.  Chapter 5 explains the way Rx handles asynchronous code and how to bridge the native .NET asynchronous types into observables. This chapter also discusses the importance of asynchronous code in the modern application and how to add periodic behavior to your programs.  Chapter 6 concentrates on the observable-observer relationship and how to control it. In this chapter, I explain the best way to create observers for various scenarios and how to limit the lifetime of the observer subscription.  Chapter 7 explains the differences between hot and cold observables and intro- duces Rx subjects. This chapter teaches you how to control the state of the observable when observers subscribe to it and how to share emissions between the observers.  Chapter 8 provides a catalog of the basic query operators provided in the Rx library. Rx is often referred to as LINQ to Events, and knowing the details of the Rx operators will help you build powerful queries that will save you time and effort.  Chapter 9 continues where chapter 8 leaves off and shows advanced ways to par- tition and combine observables. You’ll learn how to group elements by condi- tion or by coincidence and how to react to correlations between observables.  Chapter 10 delves deep into the Rx concurrency model and synchronization. I introduce the concept of schedulers and explain the schedulers Rx has to offer. Then I explain how to control the time and computation location of your Rx queries.  Chapter 11 teaches you to protect your Rx queries from faults and to react to errors that might happen in the query processing. This chapter also covers ways to manage resources that are consumed by the observables and the Rx queries. The book also has three appendices:  Appendix A summarizes the concepts of asynchronous programming in .NET.
  • 20.  Appendix B presents the Rx Disposables library and explains how to use the utilities it provides.  Appendix C explains how to test Rx operators and queries. The book is intended to be used as a guide and as a reference. If you’re new to Rx, I recommend reading from the beginning. If you’re already familiar with Rx concepts, you might find it useful to read a specific chapter based on the task you’re trying to accomplish. About the code This book contains many examples of source code both in numbered listings and inline with normal text. In both cases, source code is formatted in a fixed-width font like this to separate it from ordinary text. Sometimes code is also in bold to highlight code that has changed from previous steps in the chapter, such as when a new feature adds to an existing line of code. In many cases, the original source code has been reformatted; we’ve added line breaks and reworked indentation to accommodate the available page space in the book. In rare cases, even this was not enough, and listings include line-continuation markers (➥). Additionally, comments in the source code have often been removed from the listings when the code is described in the text. Code annotations accompany many of the listings, highlighting important concepts. The source code for this book is available to download from the publisher’s web- site (www.manning.com/books/rx-dot-net-in-action) and from GitHub (https:// github.com/tamirdresher/RxInAction). Instructions for using this code are provided in the README file included in the repository root. In the e-book, color is used in some listings and code snippets. Blue is used for primitive types and saved keywords. Aqua highlights user-defined types, and red is used for string literals. Brown is used for string parameters placeholders, and green is for comments. As always, black is user code. Author Online Purchase of Rx.NET in Action includes free access to a private web forum run by Man- ning Publications, where you can make comments about the book, ask technical ques- tions, and receive help from the author and from other users. To access the forum and subscribe to it, point your web browser at www.manning.com/books/rx-dot-net- in-action. This page provides information on how to get on the forum after you’re reg- istered, the kinds of help available, and the rules of conduct on the forum. Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It’s not a commitment to any specific amount of participation on the part of the author, whose contribution to the Author Online forum remains voluntary (and unpaid). We suggest you try asking him some challenging questions, lest his interest
  • 21. stray! The Author Online forum and the archives of previous discussions will be acces- sible from the publisher’s website as long as the book is in print. Other online resources If you’re interested in Rx, you may also want to check out the Rx portal http:// reactivex.io, which provides a Developer Center. It contains the most recent informa- tion about the library and its ports. Rx.NET is an open source project, and you can find the full code and discussions at https://github.com/Reactive-Extensions/Rx.NET. If you want to ask a question about Rx, you can visit the gitter channel (https:// gitter.im/Reactive-Extensions/Rx.NET) or the slack #rx channel, which requires you to subscribe through the sign-up page for the .NET Core Slack Channel (http:// tattoocoder.com/aspnet-slack-sign-up/).
  • 22. Part 1 Getting started with Reactive Extensions What are reactive applications? What are they good for? How does pro- gramming with Reactive Extensions (Rx) change the way you write code? What should you do before you start working with Rx? And why is Rx better than tradi- tional event-driven programming? These are the questions we’ll begin to address in these first three chapters. You’ll learn what reactive systems and applications are, and why you should care. You’ll see a real example of creating an application that uses Rx and what you need to do to create your own Rx applications. You’ll also look at the func- tional programming foundations that Rx is based on, to make it easier to under- stand the rest of the concepts that this book introduces.
  • 23. Reactive programming The reactive programming paradigm has gained increasing popularity in recent years as a model that aims to simplify the implementation of event-driven applica- tions and the execution of asynchronous code. Reactive programming concen- trates on the propagation of changes and their effects—simply put, how to react to changes and create data flows that depend on them.1 With the rise of applications such as Facebook and Twitter, every change hap- pening on one side of the ocean (for example, a status update) is immediately observed on the other side, and a chain of reactions occurs instantly inside the application. It shouldn’t come as a surprise that a simplified model to express this reaction chain is needed. Today, modern applications are highly driven by changes happening in the outside environment (such as in GPS location, battery and power management, and social networking messages) as well as by changes inside the This chapter covers  Being reactive  Thinking about events as streams  Introducing Reactive Extensions (Rx) 1 This book is about reactive programming and not about functional reactive programming (FRP). FRP can operate on continuous time, whereas Rx can operate only on discrete points of time. More info can be found at the FRP creator’s keynote, http://mng.bz/TcB6.
  • 24. 4 CHAPTER 1 Reactive programming application (such as web call responses, file reading and writing, and timers). To all of those events, the applications are reacting accordingly—for instance, by changing the displayed view or modifying stored data. We see the necessity for a simplified model for reacting to events in many types of applications: robotics, mobile apps, health care, and more. Reacting to events in a clas- sic imperative way leads to cumbersome, hard-to-understand, and error-prone code, because the poor programmer who is responsible for coordinating events and data changes has to work manually with isolated islands of code that can change that same data. These changes might happen in an unpredictable order or even at the same time. Reactive programming provides abstractions to events and to states that change over time so that we can free ourselves from managing the dependencies between those val- ues when we create the chains of execution that run when those events occur. Reactive Extensions (Rx) is a library that provides the reactive programming model for .NET applications. Rx makes event-handling code simpler and more expressive by using declarative operations (in LINQ style) to create queries over a single sequence of events. Rx also provides methods called combinators (combining operations) that enable you to join sequences of events in order to handle patterns of event occur- rences or the correlations between them. At the time of this writing, more than 600 operations (with overloads) are in the Rx library. Each one encapsulates recurring event-processing code that otherwise you’d have to write yourself. This book’s purpose is to teach you why you should embrace the reactive program- ming way of thinking and how to use Rx to build event-driven applications with ease and, most important, fun. The book will teach you step by step about the various lay- ers that Rx is built upon, from the building blocks that allow you to create reactive data and event streams, through the rich query capabilities that Rx provides, and the Rx concurrency model that allows you to control the asynchronicity of your code and the processing of your reactive handlers. But first you need to understand what being reactive means, and the difference between traditional imperative programming and the reactive way of working with events. 1.1 Being reactive As changes happen in an application, your code needs to react to them; that’s what being reactive means. Changes come in many forms. The simplest one is a change of a variable value that we’re so accustomed to in our day-to-day programming. The vari- able holds a value that can be changed at a particular time by a certain operation. For instance, in C# you can write something like this: int a = 2; int b = 3; int c = a + b; Console.WriteLine("before: the value of c is {0}",c); a=7; b=2; Console.WriteLine("after: the value of c is {0}",c);
  • 25. 5 Being reactive The output is before: the value of c is 5 after: the value of c is 5 In this small program, both printouts show the same value for the c variable. In our imperative programming model, the value of c is 5, and it will stay 5 unless you over- ride it explicitly. Sometimes you want c to be updated the moment a or b changes. Reactive pro- gramming introduces a different type of variable that’s time varying: this variable isn’t fixed to its assigned value, but rather the value varies by reacting to changes that hap- pen over time. Look again at our little program; when it’s running in a reactive programming model, the output is before: the value of c is 5 after: the value of c is 9 “Magically” the value of c has changed. This is due to the change that happened to its dependencies. This process works just like a machine that’s fed from two parallel con- veyers and produces an item from the input on either side, as shown in figure 1.1. 5 11 8 9 5 10 1 a: b: 4 1 2 + Operator Reactive Machine + Operator Reactive Machine 3 2 7 Figure 1.1 A reactive representation of the function c = a + b. As the values of a and b are changing, c’s value is changing as well. When a is 7 and b is 2, c automatically changes to 9. When b changes to 1, c becomes 8 because a’s value is still 7.
  • 26. Visit https://textbookfull.com now to explore a rich collection of eBooks, textbook and enjoy exciting offers!
  • 27. 6 CHAPTER 1 Reactive programming You might find it surprising, but you’ve probably worked with reactive applications for years. This concept of reactiveness is what makes your favorite spreadsheet application so easy and fun to use. When you create this type of equation in a spreadsheet cell, each time you change the value in cells that feed into the equation, the result in the final cell changes automatically. 1.1.1 Reactiveness in your application In a real-world application, you can spot possible time-variant variables in many cir- cumstances—for instance, GPS location, temperature, mouse coordinates, or even text-box content. All of these hold a value that’s changing over time, to which the application reacts, and are, therefore, time variant. It’s also worth mentioning that time itself is a time variant; its value is changing all the time. In an imperative pro- gramming model such as C#, you’d use events to create the mechanism of reacting to change, but that can lead to hard-to-maintain code because events are scattered among various code fragments. Imagine a mobile application that helps users find discounts and specials in shops located in their surrounding area. Let’s call it Shoppy. Figure 1.2 describes the Shoppy architecture. Figure 1.2 The Shoppy application architecture. The mobile app receives the current location from the GPS and can query about shops and deals via the application service. When a new deal is available, the application service sends a push notification through the push notifications server. One of the great features you want from Shoppy is to make the size of the shop icon bigger on the map as the user gets closer (from a certain minimal radius), as shown in figure 1.3. You also want the system to push new deals to the application when updates are available. SQL Location Application server Push notifications servers New deals Shops and deals DB
  • 28. 7 Introducing Reactive Extensions In this scenario, you could say that the store.Location, myLocation, and icon- Size variables are time variant. For each store, the icon size could be written: distance = store.Location – myLocation; iconSize = (MINIMAL_RADIUS / distance)*MinIconSize Because you’ve used time-variant variables, each time a change occurs in the myLocation variable, a change is triggered in the distance variable. The applica- tion will eventually react by making the store icon appear bigger or smaller, depend- ing on the distance from the store. Note that for simplicity, I didn’t handle the boundary check on the minimum allowed icon size, and that distance might be 0 or close to it. This is a simple example, but as you’ll see, the great power of using the reactive programming model lies in its ability to combine and join, as well as to partition and split the stream of values that each time-variant variable is pushing. This is because reactive programming lets you focus on what you’re trying to achieve rather than on the technical details of making it work. This leads to simple and readable code and eliminates most boilerplate code (such as change tracking or state management) that distracts you from the intent of your code logic. When the code is short and focused, it’s less buggy and easier to grasp. We can now stop talking theoretically so you can see how to bring reactive pro- gramming into action in .NET with the help of Rx. 1.2 Introducing Reactive Extensions Now that we’ve covered reactive programming, it’s time to get to know our star: Reac- tive Extensions, which is often shortened to Rx. Microsoft developed the Reactive Extensions library to make it easy to work with streams of events and data. In a way, a Figure 1.3 The Shoppy application view of the map. When the user is far from the Rx shop, the icon is small (on the left), and as the user gets closer, the icon gets bigger (on the right).
  • 29. 8 CHAPTER 1 Reactive programming time-variant value is by itself a stream of events; each value change is a type of event that you subscribe to and that updates the values that depend on it. Rx facilitates working with streams of events by abstracting them as observable sequences, which is also the way Rx represents time-variant values. Observable means that you as a user can observe the values that the sequence carries, and sequence means an order exists to what’s carried. Rx was architected by Erik Meijer and Brian Beck- man and drew its inspiration from the functional programming style. In Rx, a stream is represented by observables that you can create from .NET events, tasks, or collections, or can create by yourself from another source. Using Rx, you can query the observ- ables with LINQ operators and control the concurrency with schedulers;2 that’s why Rx is often defined in the Rx.NET sources as Rx = Observables + LINQ + Schedulers.3 The layers of Rx.NET are shown in figure 1.4. You’ll explore each component of the Rx layers as well as their interactions through- out this book, but first let’s look at a short history of Rx origins. 1.2.1 Rx history I believe that to get full control of something (especially technol- ogy), you should know the history and the details behind the scenes. Let’s start with the Rx logo which features an electric eel, shown in figure 1.5; this eel was Microsoft Live Labs’ Volta project logo. Figure 1.5 The Rx electric eel logo, inspired from the Volta project 2 A scheduler is a unit that holds an internal clock and is used to determine when and where (thread, task, and even machine) notifications are emitted. 3 Reactive-Extensions/Rx.Net github repository, https://github.com/Reactive-Extensions/Rx.NET. IObservable<T> Joins Projection Timeout Recovery Grouping Sampling Sharing Aggregating Filtering LINQ operators for events Event streams Schedulers Merging Throttling Windowing IScheduler Threads Cloud Dispatchers Time ISubject<T> IObserver<T> 12 6 1 5 11 7 2 4 10 8 3 9 Figure 1.4 The Rx layers. In the middle are the key interfaces that represent event streams and on the bottom are the schedulers that control the concurrency of the stream processing. Above all is the powerful operators library that enables you to create an event-processing pipeline in LINQ style.
  • 30. 9 Introducing Reactive Extensions The Volta project was an experimental developer toolset for creating multitier applications for the cloud, before the term cloud was formally defined. Using Volta, you could specify which portion of your application needed to run in the cloud (server) and which on the client (desktop, JavaScript, or Silverlight), and the Volta compiler would do the hard work for you. Soon it became apparent that a gap existed in transferring events arising from the server to the clients. Because .NET events aren’t first-class citizens, they couldn’t be serialized and pushed to the clients, so the observ- able and observer pair was formed (though it wasn’t called that at the time). Rx isn’t the only technology that came out of project Volta. An intermediate lan- guage (IL) to the JavaScript compiler was also invented and is the origin of Microsoft TypeScript. The same team that worked on Volta is the one that brought Rx to life. Since its release in 2010, Rx has been a success story that’s been adopted by many companies. Its success was seen in other communities outside .NET, and it was soon being ported to other languages and technologies. Netflix, for example, uses Rx extensively in its service layer and is responsible for the RxJava port.4 Microsoft also uses Rx internally to run Cortana—the intelligent personal assistant that’s hosted inside every Windows Phone device; when you create an event, an observable is cre- ated in the background. At the time of this writing, Rx is supported in more than 10 languages, including JavaScript, C++, Python, and Swift. Reactive Extensions is now a collection of open source projects. You can find information about them as well as documentation and news at http://reactivex.io/. Reactive Extensions for .NET is hosted under the GitHub repo at https:/ /github.com/Reactive-Extensions/Rx.NET. Now that we’ve covered a bit of the history and survived to tell about it, let’s start exploring the Rx internals. 1.2.2 Rx on the client and server Rx is a good fit with event-driven applications. This makes sense because events (as you saw earlier) are the imperative way to create time-variant values. Historically, event-driven programming was seen mainly in client-side technologies because of the user interaction that was implemented as events. For example, you may have worked with OnMouseMove or OnKeyPressed events. For that reason, it’s no wonder that you see many client applications using Rx. Furthermore, some client frameworks are based on Rx, such as ReactiveUI (http:/ /reactiveui.net). But let me assure you that Rx isn’t client-side-only technology. On the contrary, many scenarios exist for server-side code that Rx will fit perfectly. In addition, as I said before, Rx is used for large applications such as Microsoft Cortana, Netflix, and com- plex event processing (CEP) using Microsoft StreamInsight. Rx is an excellent library for dealing with messages that the application receives, and it doesn’t matter whether it’s running on a service layer or a client layer. 4 See “Reactive Programming in the Netflix API with RxJava” by Ben Christensen and Jafar Husain (http:// techblog.netflix.com/2013/02/rxjava-netflix-api.html) for details.
  • 31. 10 CHAPTER 1 Reactive programming 1.2.3 Observables Observables are used to implement time-variant values (which we defined as observable sequences) in Rx. They represent the push model, in which new data is pushed to (or notifies) the observers. Observables are defined as the source of the events (or notifications) or, if you pre- fer, the publishers of a stream of data. And the push model means that instead of hav- ing the observers fetch data from the source and always checking whether there’s new data that wasn’t already taken (the pull model), the data is delivered to the observers when it’s available. Observables implement the IObservable<T> interface that has resided in the System namespace since version 4.0 of the .NET Framework. public interface IObservable<T> { IDisposable Subscribe(IObserver<T> observer); } The IObservable<T> interface has only one method, Subscribe, that allows observers to be subscribed for notifications. The Subscribe method returns an IDisposable object that represents the subscription and allows the observer to unsubscribe at any time by calling the Dispose method. Observables hold the collec- tion of subscribed observers and notify them when there’s something worth notifying. This is done using the IObserver<T> interface, which also has resided in the System namespace since version 4.0 of the .NET Framework, as shown here. public interface IObserver<T> { void OnNext(T value); void OnError(Exception error); void OnCompleted(); } The basic flow of using IObservable and IObserver is shown in figure 1.6. Observ- ables don’t always complete; they can be providers of a potentially unbounded num- ber of sequenced elements (such as an infinite collection). An observable also can be “quiet,” meaning it never pushed any element and never will. Observables can also fail; the failure can occur after the observable has already pushed elements or it can happen without any element ever being pushed. This observable algebra is formalized in the following expression (where * indi- cates zero or more times, ? indicates zero or one time, and | is an OR operator): OnNext(t)* (OnCompleted() | OnError(e))? Listing 1.1 The IObservable interface Listing 1.2 The IObserver interface Subscribes an observer to the observable sequence Notifies the observer of a new element in the observable sequence Notifies the observer that an exception has occurred Notifies the observer that the observable sequence has completed and no more notifications will be emitted
  • 32. Random documents with unrelated content Scribd suggests to you:
  • 33. themselves, who are hastening to get out of it—are so intolerable, that hardly any amount of pay will ever be thought a full recompense for the sacrifices which a person grown up to man’s estate, and properly qualified in other respects, would be called upon to make, were he required to mess in the cock-pit. In the event, therefore, of such union of offices, the gentleman in whom they are joined ought to bear a regular commission, mess with the commissioned officers, and walk the weather side of the deck; perhaps also he might advantageously wear a suitable uniform. At all events, he ought to possess a distinct rank, and be considered as essentially a part of the ship’s complement as the surgeon, purser, or any other officer in the civil department of the fleet. People unacquainted with the nature of naval discipline may smile, perhaps, at some of the privileges glanced at above, as essential to the right exercise of power. But long experience has shewn that the distinctions in question are the recognised symbols or indexes of due subordination and general good order. They unquestionably contribute, indirectly, to the maintenance of that prompt and effective obedience, and respect to constituted authority, which, combined with self-respect, go so far to form the sinews of naval strength. If, therefore, it be of real utility to have the schoolmaster’s work as well executed as that of the other officers, it surely follows that he ought to be placed in a situation to command, not merely the dogged attention of the midshipmen, but in one which will insure the official reverence of the boys, together with a proportionate degree of consideration from those whom they command. If these minute particulars in balancing the scales of discipline be not duly attended to, the respect of the pupils will dwindle into familiarity, and the schoolmaster, if he be not a strong-minded person, may end by losing his own self-confidence. All lessons then become a farce, and the teacher either relapses into a useless appendage to the ship, or, if forcibly sustained by the stern authority of the captain, he is apt to degenerate into a mere pedagogue. It may safely be laid down as a pretty general principle, that to render any man of much use, he must be placed permanently in a station, which of itself, and by the ordinary workings of the
  • 34. established order of things, will insure attention both from superiors and inferiors. Without this adjustment, there can be no good service performed any where—on land or at sea. It is sometimes not sufficiently recollected, that schooling on board ship differs materially from what it is on shore; for it not only treats of very different matters, but has other objects in view, both immediate and remote. Before a young person actually engages in a profession, the great purpose of a school appears to consist in mere training—that is to say, in carrying his faculties through a course of preparatory discipline, without any more specific object than mental exercise. But when the youth is once fairly embarked in the pursuit which is to furnish employment for his life, an immediate modification takes place. The system which it is necessary to follow at sea is then placed in distinct contrast to that previously observed. On shore, education and business are two separate things, one of which does not begin till the other ends; while, on board ship, the two always go hand in hand. As the lessons of the teacher may be put in practice immediately, the utility of theoretical knowledge is exhibited on the spot; and thus a gradually increasing impulse is given to the whole course of study. A boy who learns from his master what the word Latitude means, and what is the method of obtaining it, instantly runs upon deck, takes a quadrant in his hand, observes the sun’s meridional altitude, and is filled with amaze and delight on discovering: within what small limits he has been able to determine the ship’s place relatively to the equator. Next day he sets to work with increased eagerness to conquer the more difficult problem of finding the Longitude, which he has immediate opportunities of bringing to the test of actual experiment. The theory of Gunnery, likewise, when studied by itself, is frequently found to be intricate, and often far from satisfactory; but, when all its results can be brought to the test of experiment, the aspect which this very important pursuit assumes is totally different. How few officers, for instance, understand correctly the meaning of the elementary term Point Blank, or have any useful conception of the mathematical principles which it involves! How often do we hear people gravely assuming that the shot rises between the gun and the point-blank
  • 35. mark! The laws which regulate the action of fluids directed against plane surfaces are by no means easily explained when grappled with alone; but, when brought to bear on the use of the rudder, or the trim of the sails, there is hardly a boy afloat who fails to appreciate the value of true science over what is called ‘rule of thumb;’ or rather, who may not soon be taught to feel the mighty advantage of uniting the two, so as to make theory and practice mutually assist each other. Nearly the same thing may be said of almost every other branch of knowledge: with languages, for instance—I mean more particularly the modern languages—French, Spanish, Portuguese, and Italian, most of which are made to tell generally as soon as acquired. The Mathematics in all their wonderful branches, and Science in almost every department, furnish ample objects to fill up the leisure hours of an officer. Geography, history, and the law of nations, come into professional play at every turn. A young man, therefore, of any capacity or industry, is nearly sure of rendering himself useful in a short time, be his particular pursuits what they may, provided only that his zeal is duly encouraged by the captain, and seconded by the ready assistance of a properly qualified preceptor whom he has been taught to respect. It must never be forgotten, however, that along with all this knowledge of a professional, literary, or scientific nature, there ought to be mixed up instructions of a still more important description, upon which the formation of a young man’s character will mainly depend, whether we view him merely as an officer, or in his wider capacity as a member of the civil community. Every one acquainted with the difficult task of bringing boys safely through the intricate labyrinth of temptations which must be encountered in the early stages of a sea life, will acknowledge, that the superintendent of a young man’s habits has little or no chance of success, unless he can secure the confidence of his pupil. I very much fear, however, that there can be little hope of establishing such a relation between them, unless the preceptor be truly the superior, not only in station but in attainments, and unless it be his peculiar study to acquire this ascendency over his pupil’s mind, in order to the better regulation of his manners. I use the word manners in its
  • 36. largest sense; and it is clear that, unless the schoolmaster have leisure to keep these objects constantly in view, he cannot hope to gain the proper degree of influence over any boy’s mind. As chaplain of the ship, however, his religious duties, so far from interfering with the objects alluded to, would blend admirably with all of them, and furnish the best means, and, if it were needed, the best excuse, for a judicious and parental sort of interference. To expect that any such interference of the schoolmaster, under the present system, can be efficacious, is, I much fear, a complete delusion; and this furnishes a strong reason for uniting in one person the kindred duties of chaplain and teacher. It shews, at the same time, how inefficient any such union must be, unless care be taken to secure fitting persons to fill a joint office of such delicacy. There is still another, and by no means an unimportant benefit, which might arise to the naval service from this improvement: I mean its effect on the higher classes of officers. If there be nothing more shocking than a disreputable clergyman in a mess-room, so, on the other hand, I conceive there can be nothing more useful, in many very material respects, than the constant companionship of a right- minded and well-educated person of this description. I say nothing of the obvious and salutary influence which his presence never fails to exercise over the manners of men, already too much disposed to laxity in their habits; but it may be well to consider, likewise, the great additional benefits which may arise to the officers from their possessing the means of instructing themselves in the different branches of knowledge, with which a chaplain, regularly qualified to teach, would be able to impart. Except on board ship, and at sea, few of the senior officers of the Navy, in war time, have the opportunity, and still fewer the means, of improving their acquaintance with those pursuits, of which, in the earlier periods of their service, they may have gained a smattering. I allude to the classics, to modern languages, and the belles lettres generally, to the higher branches of mathematics, and to many of those sciences formerly deemed abstruse, but which have lately become popular; such as chemistry, geology, and natural history in all its departments.
  • 37. The time is not remote when it was held by high naval authorities, that all or any of these refinements, instead of being useful to an officer, actually stood in his way; and, as far as they went, interfered with the due execution of his duty. Nor can it, or ought it, to be denied, that the principle of extra instruction is very apt to be carried too far, and the refining system overdone. Nor must it ever be forgotten in these discussions, that the service—that is to say, the hard, regular, seamanlike round of official duties, in all seasons, and under all circumstances, ought always to be the primary objects of an officer’s thoughts, before which every thing else is not only to bend, but, if need be, must break. And it is chiefly on the principle of rendering an officer only the more fit for such technical routine, that any of the pursuits alluded to can ever be considered as having legitimate claims on his attention. If such studies become so engrossing as to detach his thoughts from his sterner duty; to make him a scholar instead of a seaman, a dandy instead of a disciplinarian; or if he allow himself to attend to these extraneous matters with any other view than to his improvement as a strictly professional man, he will, of course, find them, one and all, prejudicial, and not be encouraged. Under proper regulation, however, there seems little or no danger of any thing of this description proving injurious to an officer’s character, as a useful, hard-working servant of the public. It was formerly thought, that high-born, high-bred, and even well- educated men, were less fitted to make good officers for the ordinary course of professional work, than persons who had sprung from a lower origin, or whose education was limited to the mere technicalities of the profession, and who were without taste and without manners—men of the Hawser Trunion school, in short. But the copious experience of the late arduous war seems to have shewn, both in the army and in the navy, that the contrary is the true state of the case. And certainly, as far as my own observation and inquiries have gone, I have found reason to believe that those officers who are the best informed and the best bred, and who possess most of the true spirit of gentlemen, are not only the safest to trust in command over others, but are always the readiest to yield that prompt and cheerful obedience to their superiors, which is the
  • 38. mainspring of good order. Such men respect themselves so justly, and value their own true dignity of character so much, and are at all times so sensitively alive to the humiliation of incurring reproach, that they are extremely cautious how they expose themselves to merited censure. From the early and constant exercise of genuine politeness, they become habitually considerate of the feelings of others; and thus, by the combined action of these great principles of manners, officers of this stamp contrive to get through much more work, and generally do it much better, than persons of less refinement. Moreover, they consider nothing beneath their closest attention which falls within the limits of their duty; and, as a leading part of this principle, they are the most patient as well as vigilant superintendents of the labours of those placed under their authority, of any men I have ever seen. It is not that they watch their inferiors with a view to entrap and pounce upon them, but solely with the public-spirited and generous object of keeping all parties right, in order, by checking errors in the outset, before they have grown into crimes, to prevent the hard necessity of punishment. This is a pretty fair sketch of the method of acting observed by a thorough-bred, gentlemanlike, well-instructed officer; and every one who has been in command, and in protracted difficulties, or has merely been employed in the ordinary course of service, will readily admit that, with the assistance of such men, every department of his duty has gone on better and more pleasantly than it could have possibly done if the persons under his command had been of a coarser stamp. It is quite true that the full degree of refinement alluded to can hardly ever be fully taught on board ship. But it may often be approximated to good purpose. It is quite within our power, for example, so to train up young men, that they shall gradually acquire not only that sort of knowledge, but also those habits, which experience has shewn to have the most direct tendency to enlarge the understanding, and to chastise the taste. Precisely as this amount of intelligence increases, so will the capacity of an officer to do good service increase likewise; and it is absurd to suppose that
  • 39. he will be less disposed to do his duty well, from knowing better how to comply with its obligations. Weak minds and perverse dispositions, under any system of instruction or of discipline, will, of course, defeat these calculations; and there will, therefore, always be many effeminate and idle persons in a fleet, who, by mistaking mere acquirements for the knowledge of how to turn them to useful account, deserve the title they receive of ‘the King’s hard bargains.’ But, taking the average run of officers in the Navy, it may safely be expected, that if, in other respects, they are kept to their duty, and if they themselves have a real interest in the service, the more information they can acquire upon every subject worthy of a gentleman’s attention, the better will they be fitted for the performance not only of those higher exploits which all the world understand and admire, but even of those humble and unseen professional avocations, which make up by far the greater and the most important part of our daily duties. If, then, we can furnish all ranks of our naval officers afloat with a ready and agreeable means of filling up their time, of which most of them have a good deal to spare, we may fairly hope that they will not be slow to avail themselves of the opportunities placed within their reach. In order, however, to render these measures of any extensive utility, this plan of furnishing assistance must be carried a long way. A chaplain-schoolmaster should be allowed even to the smallest class of ships on board which, by any contrivance, the proper degree of accommodation can be obtained. And if these ideas were followed up in the admirable spirit with which some recent improvements have been carried into effect in the Navy, for instance, in the discipline, victualling, payment of wages, ratings, and other matters, a very great boon would be conferred on the service. It is not likely that the measure proposed would materially augment the expenses of the Navy, if, indeed, it had that effect at all; since both a chaplain and schoolmaster are expressly allowed to all ships, from the first to the sixth class, inclusive. But, even supposing the expense were to be augmented, there can be no doubt, I should conceive, in the mind of any person who has reflected seriously on these subjects, that the return for such outlay would be speedy and
  • 40. certain. The religious, moral, and intellectual character of officers, on whose good conduct so much depends, must, in every conceivable state of things, be an object of material consequence to the country. And it were really almost a libel on the nation, to imagine that they would not cheerfully agree to the additional expenditure which might be required, if the advantages be such as are stated. There can be no truer economy, than expending money for the promotion of virtue and sound knowledge amongst this class of public servants. For their duties, it must be recollected, generally lie so far beyond the reach of ordinary scrutiny, that almost the only security we have for their good conduct rests on their own sense of honour. A dishonest officer on a foreign station might often divert from its proper purpose, by a single stroke of his pen, and without much danger of detection, more of the public money than would furnish the Navy with chaplains and schoolmasters for ten years. It is to accomplish only one-half the great task of instruction merely to fill a boy’s head with technical information—his principles and habits ought to be likewise taken into our safe keeping. It is also greatly to be desired, that, when the period arrives at which he is expected to become, as it is called, his own master, he should find no difficulty in continuing, from choice, those pursuits to which he had previously applied himself on compulsion, or merely as a means of promotion. And there seems to be no method more likely to accomplish this desirable purpose, than affording the young commissioned officer the companionship of an instructor, or, at all events, of a person whose duty it should be, if required, not only to continue, in the ward-room, the course of information commenced in the cock-pit, but whose aim ought to be, so to modify these studies as to adapt them to the altered circumstances of the pupil, and to win his attention to their pursuit by rendering them agreeable and useful. It is not pretended, by any means, that such a task is an easy one; on the contrary, it will require not only considerable abilities, but high attainments, and no inconsiderable degree of good taste, together with a long apprenticeship of self-discipline, and an exclusive application to these arduous duties, as the grand object and business of the instructor’s life.
  • 41. There really appears, however, to be no situation but that of a clergyman which offers any reasonable chance of these conditions being fulfilled. And as the education of such a person is necessarily expensive, and the double office which it is proposed he should fill, one of great responsibility, labour, and difficulty, as well as one of peculiar and irremediable discomfort and privation, without any of those energetic excitements which stimulate every other class of officers to exertion, the remuneration ought clearly to be very considerable, otherwise no set of properly qualified men will engage permanently in its pursuit. A distinct class of officers, of this sacred character, although as yet they do not exist, might be readily created. If the emoluments of the chaplain of a man-of-war were respectable, the situation rendered as agreeable, in point of comfort, as the nature of the elements will admit of, and if the prospects of future provision be made certain, or contingent only upon a right performance of duty, there cannot, I think, be a doubt that, in a short time, there would be an ample and steady supply of chaplains, as highly qualified, in point of attainments, as the Admiralty might choose to fix on the scale. If this important professional object were once fairly carried into effect, we should probably soon discover an improvement in the whole system of naval discipline, the best evidences of which would be, the increased efficiency of the whole service, arising out of the gradually ameliorated habits and higher intellectual cultivation, as well as improved tastes and more rational happiness, of every class of the officers, from the oldest captain down to the youngest first- class boy, just untied from his mother’s apron-string. In all that has been said, I have taken into view almost exclusively the advantages which would accrue to the officers from the adoption of this plan of uniform instruction. It is to them, individually as gentlemen, and collectively as a body, upon the certainty of whose hearty exertions the government can at all times depend, that the country must ever look for that energetic momentum in our naval strength, upon which the national power, in this department, essentially rests. Surely, however, it is not too much to say, as a matter of experience, that the influence of a resident clergyman on
  • 42. board ship, wherever there is one, over the minds of the crew, is felt to be quite as salutary, when properly exercised, as it is to the labourers in any parish of the empire. It signifies nothing to say that the structure of naval discipline is widely different from the civil administration of the land; for the very same principles, and, more or less, the very same motives to right or wrong action, must always be in play in both cases. A judicious chaplain, therefore, who shall have become acquainted by personal experience with the habits, tastes, feelings, and pursuits of the seamen, may undoubtedly contribute an important share to the efficiency of the whole of our naval system. So far from interfering with, or in any way checking the strict course of nautical affairs, I conceive that the chaplain’s influence, rightly exercised, acting in cordial understanding with the captain, and sanctioned by his authority, might advance the best interests of the service by greatly diminishing offences, and thus lessening the melancholy necessity of punishments. Whenever this benevolent purpose can be effected, in a greater or less degree, both those who obey and those who command are sure to be better pleased with one another, and, it is reasonable to suppose, far more desirous of co-operating heartily in the accomplishment of the common purpose for which they are brought together. END OF THE FIRST VOLUME. LONDON: J. MOYES, TOOK’S COURT, CHANCERY LANE. FOOTNOTES:
  • 43. [2] I quote from a paper on the State of Education in the British Navy, printed in the United Service Journal, Part XI. for October 1830. The performance and the promise of the very rising officer, who wrote this article, help to furnish the fairest practical answer to those who object to the early advancement of young men of rank in the Navy.
  • 44. Transcriber’s Notes pg 219 Changed: when on board passage vesssels to: when on board passage vessels pg 225 Changed: half of sound snoose to: half of sound snooze pg 308 Changed: as the captian can ameliorate the habits to: as the captain can ameliorate the habits
  • 45. *** END OF THE PROJECT GUTENBERG EBOOK FRAGMENTS OF VOYAGES AND TRAVELS, INCLUDING ANECDOTES OF A NAVAL LIFE *** 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
  • 46. THE FULL PROJECT GUTENBERG LICENSE
  • 47. 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.
  • 48. 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
  • 49. 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™.
  • 50. 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
  • 51. 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
  • 52. 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