31,19 €
If you’re struggling to handle a large amount of data and don’t know how to improve your code readability, then reactive programming is the right solution for you. It lets you describe how your code behaves when changes happen and makes it easier to deal with real-time data. This book will teach you what reactive programming is, and how you can use it to write better applications.
The book starts with the basics of reactive programming, what Reactive Extensions is, and how can you use it in JavaScript along with some reactive code using Bacon. Next, you’ll discover what an Observable and an Observer are and when to use them.You'll also find out how you can query data through operators, and how to use schedulers to react to changes.
Moving on, you’ll explore the RxJs API, be introduced to the problem of data traffic (backpressure), and see how you can mitigate it. You’ll also learn about other important operators that can help improve your code readability, and you’ll see how to use transducers to compose operators.
At the end of the book, you’ll get hands-on experience of using RxJs, and will create a real-time web chat using RxJs on the client and server, providing you with the complete package to master RxJs.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 294
Veröffentlichungsjahr: 2017
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: May 2017
Production reference: 1240517
ISBN 978-1-78646-338-8
www.packtpub.com
Author
Erich de Souza Oliveira
Copy Editor
Safis Editing
Reviewer
Kevin Earley
Project Coordinator
Sheejal Shah
Commissioning Editor
Amarabhab Banerjee
Proofreader
Safis Editing
Acquisition Editor
Shweta Pant
Indexer
Francy Puthiry
Content Development Editor
Jason Pereira
Graphics
Jason Monterio
Technical Editor
Leena Patil
Production Coordinator
Shantanu Zagade
Erich de Souza Oliveira is a developer with 10 years of experience, mostly in JavaScript, Scala, and Java. He has already worked for big companies and start-ups and currently works as a Chief Technology Officer for a brazilian video platform, called Winnin.
He is the author of Studio.js (microservices library for JavaScript) and can be found talking and attending South American conferences. He has a special interest in functional reactive programming, micro services, information retrieval, and recommender systems.
Kevin Earley has always been passionate about technology. In high school, he picked up programming as a hobby. After high school, he entered the United States Air Force, where he was an electronic technician for about 9 years.
While in the USAF, he had multiple opportunities to program several utility applications for his shop. Later, Kevin left the USAF to begin a career in software development with his best friend, Mark Bowren.
Over the last 22 years, Kevin has worked for multiple companies across dozens of industries. Kevin has worked with many different technologies, but his primary expertise is with Microsoft products.
Among Kevin’s skills and talents is writing, especially technical and factual writing. Over the years, Kevin has had many opportunities to write professionally--things such as technical manuals, tests, and some religious studies. His interest in writing is what brought Kevin to Packt. One day, when he retires, Kevin hopes to write a great deal more.
Kevin currently resides in Chicago, Illinois, with his three young children, Noelani, Eliana, and Matthew “Max” Alexander.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at www.amazon.com/dp/1786463385.
If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
What Does Being Reactive Mean?
The reactive paradigm
Why do I need it?
Installation of tools
Node.js
bacon.js
RxJS
Your first code using reactive programming
Summary
Reacting for the First Time
The bacon.js observables
Creating our first observable
Observables from DOM events (asEventStream)
Observables from promises (fromPromise)
Observable node event emitter (fromEvent)
Observables from an array (fromArray)
Observables from an array (sequentially)
Observables from an interval (interval)
Observables from other sources
Properties
Changes in an observable
Reacting to changes
Subscribing
Subscribing using the onValue() method
Subscribing using the log method
Subscribing using the assign method
Acting when an error occurs
Reading how an operator works
Transforming events using bacon.js
Reusing observables
Observables' lazy evaluation
Summary
A World Full of Changes - Reactive Extensions to the Rescue
RxJS observables
Difference between bacon.js and RxJS observables
Hot and cold observables
Installing RxJS
Creating an observable
Creating an observable from iterable objects
Creating an observable from a sequence factory
Creating an observable using range ()
Creating an observable using period of time
Creating an observable from callbacks
Creating an observable from a promise
Creating empty observables
Creating an observable from a single value
Creating an observable from a factory function
Creating an observable from arbitrary arguments
Creating an observable from an error
Creating observables from DOM events (or EventEmitter)
Creating an observable from an arbitrary source
Subscribing to changes (Observer)
RxJS Subjects
RxJS Disposable
RxJS Schedulers
Summary
Transforming Data - Map, Filter, and Reduce
Adding operators to observables
The map() operator
The flatMap() operator
The filter() operator
The reduce() operator
Summary
The World Changes Too Fast - Operators to Deal with Backpressure
What is backpressure?
Common strategies to deal with backpressure
Lossy strategies to deal with backpressure
The throttle() operator
The sample() operator
The debounce() operator
The pausable() observables
Loss-less operators to deal with backpressure
Buffering
The bufferWithCount() operator
The bufferWithTime() operator
The bufferWithTimeOrCount() operator
Pausable observables (with buffer)
Controlled observables
More ways to filter data
The first() operator
The take() operator
The takeLast() operator
The takeWhile() operator
The skip() operator
The skipWhile() operator
Summary
Too Many Sources - Combining Observables
When do I need to combine observables?
Running observables
Concatenating observables
Using the concat() operator
Using the merge() operator
Using the concatAll() operator
Using the mergeAll() operator
Combining observables
Using the forkJoin() operator
Using the zip() operator
Using the zipIterable() operator
Summary
Something is Wrong - Testing and Dealing with Errors
Dealing with errors
Acting when an error occurs
Treating an error
The catch() operator
The onErrorResumeNext() operator
The retry() operator
The mergeDelayError() operator
Testing our application
Testing in the server
Testing in the browser
Testing applications using RxJS
Summary
More about Operators
The road so far
The fundamentals of RxJS
The map() operator versus the flatMap() operator
Challenge - Creating a function to filter elements using only the flatMap() operator
Filtering data
Aggregating data
Going beyond the basics
Dealing with backpressure
Combining observables
Other important operators
The flatMapLatest() operator
The flatMapFirst() operator
The finally() operator
The groupBy() operator
The do() operator
Summary
Composition
What is a transducer?
Available transducer implementations for JavaScript
The transducers-js API
Using transducers
Using transducers with RxJS
Testing transducers
A performance comparison for JavaScript code using transducers
Summary
A Real-Time Server
The web chat server
Creating the project
The architecture of the server
Implementing the server
DataSource
Service to send messages
Test implementation
Service implementation
Service to listen to new messages
Test implementation
Service implementation
Service to block messages from a given user
Test implementation
Service implementation
Service to send a command
Test implementation
Service implementation
Handling WebSocket connections
Scaling the server
Connecting to Redis
Using Redis as the DataSource for messages
Summary
A Real-Time Client
Installing dependencies
The structure of our client
Building the application for the first time
Connecting to the server application
Using RxJS to manage user input
Connecting user interactions and server communication
Improving interaction with RxJS
Batching changes to the DOM
Testing the application
Summary
Does creating a live application to handle thousands of sources of real-time data sound hard to you? No more. Teach yourself some reactive programming, and you will be able expand your boundaries, creating applications empowered with real-time data without compromising performance.
Chapter 1, What Does Being Reactive Mean?, explains the basics of reactive programming and how it compares with imperative programming, and also shows some example usage.
Chapter 2, Reacting for the First Time, covers the basics of event streams and operators using bacon.js.
Chapter 3, A World Full of Change - Reactive Extensions to the Rescue, in this chapter we explore the definitions and types of Observers and Observables.
Chapter 4, Transforming Data - Map, Filter, and Reduce, covers the most basic and important operators from functional reactive programming.
Chapter 5, The World Changes Too Fast - Operators to Deal with Backpressure, explains different techniques to mitigate the problem of receiving data faster than you can process it.
Chapter6,Too Many Sources? - Combining Observables, teaches you to combine different sources of data to create new ones.
Chapter7, Something Is Wrong - Testing and Dealing with Errors, explains how to deal with errors in observables and how to test programs using functional reactive programming.
Chapter8, More about Operators, shows some important operators that did not fit into the previous chapters.
Chapter9, Composition, explains what a transducer is and why you should use it.
Chapter10, A Real-Time Server, builds the backend part of an web chat application used as an example of functional reactive programming.
Chapter 11, A Real-Time Client, builds the frontend part of an web chat application used as an example of functional reactive programming.
All you need to follow this book is a computer with a version of Node greater than 6 installed. All software mentioned in this book is free of charge and can be downloaded from the Internet.
This book is written for developers with basic JavaScript knowledge. We will use ES6 and functional reactive programming to create beautiful and readable applications. Here you will learn how to deal with an infinite stream of data (such as using tweets, stock info, or even chat messages) without ever compromising your system performance.
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text, folder names, filenames, file extensions, pathnames are shown as follows: Open the file index.js.
A block of code is set as follows:
function hello(){ console.log(“Hello World”);}
Any command-line input or output is written as follows:
npm install
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "In order to download new modules, we will go toFiles| Settings|Project Name|Project Interpreter."
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-Reactive-JavaScript. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
If you have bought this book, you have probably already heard about reactive programming (or even functional reactive programming). Nowadays, a lot of developers claim to use it in their own project; it is also easy to find posts on the Internet saying how amazing it is when compared with older paradigms. But, know you are doing a great job with the tools you have in your hands.
Learning a new programming paradigm is really hard. Most of the time you don't even know you needed it before you already mastered it, and you always have to ask yourself if this is really something that is worth the hours of studying or if it is just a new buzzword that all the cool kids are talking about, without adding real value to your programming skills.
Maybe you have tried reactive programming before, even used it in a small project or, like me, you just thought it wasn't worth a try, but for some reason you decided to give the paradigm an opportunity, (you are always thirsty for knowledge, I know, I was in your shoes a couple of years ago). It took me a lot of time to understand why I needed reactive programming and how to master it. I want to make sure that you have an easier path than I had.
This book will guide you through the reactive programming principles, and using a lot of examples, I will show you how to process and combine different sources of data or events to create astonishing live applications. In this first chapter, we are going to use the bacon.js library just to understand the basics and then we will go deeper with Reactive Extensions (RxJS).
Before we dive into programming, you need to understand what reactive programming is and the problems it is designed to solve.
This chapter will cover the following points:
Understanding what reactive programming is
Comparison between reactive programming and imperative programming
Knowing what problems reactive programming solves
Installation of the tools needed throughout this book
The first example of functional reactive programming will use a JavaScript library
Functional reactive programming is especially useful when implementing one of these scenarios:
Graphical user interface
Animation
Robotics
Simulation
Computer vision
A few years ago, all a user could do in a web app was fill a form with some data and post it to a server. Nowadays our web apps and mobile apps present to the user a richer interface, empowering them with real-time information and giving a lot more interaction possibilities. So, as the applications evolved, we needed more tools to achieve the new requirements.
Using it you can abstract the source of your data to the business logic of your application–this lets you write more concise and decoupled code, improves the reuse, and leads to a more testable code as you can easily mock your streams to test your business logic.
In this book we will use Reactive Extensions to explain and implement an example reactive application. Reactive Extensions are widely used in the industry and they have implementations for different languages (.Net, Scala, JavaScript, Ruby, Java, and so on) so you can easily translate the things you learn in this book to other languages.
In my personal opinion, Reactive Extensions have some concepts which are hard to understand for those unfamiliar with reactive programming. For this reason, we will learn the basics using a more simple library (bacon.js), and as soon as you understand the basics and the concepts, I will give you more tools using RxJS.
Before we start to use reactive programming, we need to install the tools we will be using throughout this book.
We will be using node version 6.9.1, the most recent LTS version of nodes at the time of writing. You can find versions of it for Windows, Mac, and Linux at the following link:
https://nodejs.org/en/download/releases/.
In this first chapter of this book we will be usingbacon.js, which is a library for functional reactive programming in JavaScript. This library works in both server and client. We will use it to introduce you to some concepts of functional reactive programming as it is easier to get started. We will be using version 0.7.88.
To install it on your server, just run the following command inside a node project:
npm
i
-
save
To add it to an HTML page, just paste the following code snippet inside it:
<script src="https://cdnjs.cloudflare.com/ajax/libs/bacon.js/0.7.88/Bacon.min.js"> </script>
The last tool we need to follow in this book is RxJS; we will use this library in later chapters. This library also runs in both client and server and we will be using version 4.1.0.
To install it on your server, just run the following command inside a node project:
npm i [email protected] -save
To add it to an HTML page, just paste the following code snippet inside it:
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.all.js">
</script>
