38,39 €
Get up and running with reactive programming paradigms to build fast, concurrent, and powerful applications
If you are a .NET developer who wants to implement all the reactive programming paradigm techniques to create better and more efficient code, then this is the book for you. No prior knowledge of reactive programming is expected.
Reactive programming is an innovative programming paradigm focused on time-based problem solving. It makes your programs better-performing, easier to scale, and more reliable.
Want to create fast-running applications to handle complex logics and huge datasets for financial and big-data challenges? Then you have picked up the right book!
Starting with the principles of reactive programming and unveiling the power of the pull-programming world, this book is your one-stop solution to get a deep practical understanding of reactive programming techniques. You will gradually learn all about reactive extensions, programming, testing, and debugging observable sequence, and integrating events from CLR data-at-rest or events. Finally, you will dive into advanced techniques such as manipulating time in data-flow, customizing operators and providers, and exploring functional reactive programming.
By the end of the book, you'll know how to apply reactive programming to solve complex problems and build efficient programs with reactive user interfaces.
This is a concise reference manual for reactive programming with Rx for C# and F# using real-world, practical examples.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 301
Veröffentlichungsjahr: 2016
Copyright © 2016 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 authors, 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: July 2016
Production reference: 1150716
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78588-288-3
www.packtpub.com
Authors
Antonio Esposito
Michael Ciceri
Copy Editors
Akshata Lobo
Reviewer
Uladzimir Kazakevich
Project Coordinator
Ritika Manoj
Commissioning Editor
Amarabha Banerjee
Proofreader
Safis Editing
Acquisition Editor
Larissa Pinto
Indexer
Rekha Nair
Content Development Editor
Arun Nadar
Graphics
Jason Monteiro
Technical Editor
Sachit Bedi
Production Coordinator
Aparna Bhagat
Antonio Esposito is a Microsoft Certified Trainer, software architect, father, son, and lover of cooking and eating. He has been addicted to computer programming from age 8, a developer since 2002, and a speaker from 2010. He has moved across Europe in the last fifteen years working as freelance consultant or speaker for companies such as UniCredit Bank, Ferrari F1 Racing Team, Microsoft Italy, IBM, and many others. He actively attends as a speaker at a lot of conferences, such as MCT Summit and WPC Italy. He is already an author for Packt with Learning .NET High Performance Programming in 2014.
To my children Tommaso and Matteo, and my lovely wife Giusy, who supported me during my many and many nights of writing.
Michael Ciceri is a technology consultant in .NET Framework and Microsoft. He is a functional programming, mathematics, technology, psychology, and science enthusiast. He started as an autodidact and passionately became an analyst and software developer in several areas, such as image processing, banking ATM services security, intranet back end, app monetizing. Recently, he has been working on the analysis and development of functions in the core application to solve problems or improve capabilities.
Uladzimir Kazakevich has been writing code for as long as he can remember. He is a developer, consultant, and solution architect. With over 15 years of experience in delivering solutions across industry sectors, such as social media, education, e-commerce and finance, he specializes in technologies, such as Microsoft .NET, WebAPI, Windows Communication Foundation, MSSQL, Microsoft Azure, scalable and high-performant infrastructure. He is certified by SEI as Software Architecture Professional and is TOGAF 9-certified.
Uladzimir serves as Head of EPAM Microsoft Competency Center with focus on Solution Architecture. His key focus is to harness, develop, and scale innovative technologies and engineering methodologies in the company, competency center and successfully apply them in client engagements.
When he codes for fun, he spends his time using Arduinos, sensors, Raspberry Pis, and Azure Machine Learning to build own house automation system. He is also the organizer of local TechTalks and SETCON conferences; he is also an active speaker at such events.
Uladzimir lives in Brest, Belarus, with his wonderful wife Alena and their awesome little girl Nika.
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://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Reactive programming is the programming paradigm for handling continuous changing messages and their notifications. Instead of developing static value changes, we develop data changes. This slight difference leaves the developer facing issues regarding high speed messaging systems that handle such messages in a completely new way. Reactive programming means writing functions that transform messages. This means that something, such as an exception within the reactive world became a message. This book will cover Reactive programming with Reactive extensions for .NET in an increasing complex approach. In the final chapters, the reader will find real-world solutions and learn about F# functional reactive programming.
Chapter 1, First Steps in Reactive Programming, covers what Reactive programming is: the idea, the overall design, the available frameworks, and the languages supporting this incredible programming paradigm.
Chapter 2, Reactive Programming with C#, will show Reactive programming in action in plain C# coding without the need for any external reference. In this way, any developer may bring reactive programming knowledge to any existing application.
Chapter 3, Reactive Extension Programming, explains RX basics, such as the Observable sequence, message consumers (Observer), and the most widely used reactive operators, such as message transforming and message grouping functions.
Chapter 4, Observable Sequence Programming, will teach you how to produce, consume, and route messages with subjects and learn the Rx operator catalog. You will also see operators that apply message filtering, aggregation, transformation, generation, and time-based operations.
Chapter 5, Debugging Reactive Extensions, will deal with debugging and tracing observable sequences. It focuses on handling exceptions, routing errors, and notifying users about application issues in order to improve application reliability and maintainability.
Chapter 6, CLR Integration and Scheduling, covers how to source or send messages with plain CLR objects and how to achieve time scheduling and multithreading easily with Rx programming.
Chapter 7, Advanced Techniques, will show Rx in action with real-world solutions and explain how to create new operators or how to use the Rx features in classic .NET development.
Chapter 8, F# and Functional Reactive Programming, presents the F# language and key points of functional programming. It describes Functional Reactive Programming (FRP) with a few examples of push-based and pull-based scenarios, the event data flow, and type events in F#.
Chapter 9, Advanced FRP and Best Practices, delves deep into advanced FRP concepts through the study of discrete and continuous components and the concepts of time flow and dynamic change. It also discusses Railway-oriented programming and F# observable.
For this book, you will require an updated version Visual Studio 2013 or 2015.The Reactive Extensions library pack is available from the NuGet package explorer by searching "Rx-main". Examples from the book require other packages as well; in these cases, a reference within the chapter itself will specify the required package's name.
If you are an experienced C# developer with no pre-existing knowledge of Rx development, this book is for you. The book is useful as a Rx reference manual.
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:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Reactive-Programming-for-.NET-Developers. 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.
Changing the application state is not something wrong by itself, but there are different programming approaches that may produce better results and together give the developer a more pleasant working experience. A typical use case happens when we deal with in-move data (or living data or data stream), where we may find that using interaction logic constructs that change state, such as if, for, and so on, is a poor performing choice together with a poor design. In-move data is any kind of data stream, such as a video stream, an application insights stream, and so on. Because of its statelessness, it is obvious that a stateless programming approach offers better results than a state-driven one.
We are used to dealing with static data, such as a variable, a database, or anything else such as some binary- or string-based data. All such data is data-at-rest, static data, or simply data.
As an example if we execute a select statement against a relational database, we will always have a result set containing the exact value contained in the database table at the specific time we executed the query. A second later, the table could experience an update statement that could change any row's data without the first client (the one executing the select statement) receiving an update on such data changes. To address these kinds of data changes without having to face issues between different relational database clients, there are optimistic and pessimistic concurrency checks (a bit outside the scope of this book). Obviously, the less we need to synchronize code to access a concurrent resource, the better our code will perform.
In imperative programming, control-flow is responsible for the good execution of the application. Such flow is usually made of multiple code rows that do something on input/output ports and somehow alter the application's state until the desired result is achieved, whereas in dataflow programming, data flows in and out of the different stages of a flowchart, as it behaves in a workflow.
Obviously, the different types of programming will greatly change the developers' experience and programming capability of the language. It is very difficult (and conceptually a bit wrong) to compute something by executing some interaction logic in data flow programming, because this kind of programming is simply outside the core design of the programming paradigm.
A practical example can be seen in data integrational , Extract, Transform, and Load (ETL) workflows, such as those available in SQL Server Integration Services (SSIS), as shown in the following screenshot. An ETL workflow has the task of reading (extracting) data from a data source (relational or not) and mapping (transforming) such data by grouping or aggregating it with other data sources or by executing transforming functions. Then, data flows (loads) into a target data store (relational or not) for future simplified access. SSIS is the tool for designing these kinds of workflows within the SQL Server Business Intelligence suite.
A SSIS dataflow task doing some transformations on data from a relational database
Generally speaking, outside the SQL server-oriented implementation of SSIS, within data flow programming, instead of having a huge code base in a high-level code, we have something like a data workflow. A digraph (directed graph)—an ordered version of a usual flowchart. Here is an example:
A simple representation of a dataflow digraph made of three recurring stages
Within the Microsoft universe, the only data flow programming compliant language is the Microsoft Visual Programming Language available for the Microsoft Robotics Developer Studio environment for robotics programming. Instead, SSIS simply uses data flows to handle data integrations between databases.
The unavailability of the state, a key concept of data flow programming, is the opposite of what happens in all imperative or object-oriented programming-based applications. This behavior drastically changes the programming experience.
A stateless design never stores (temporary or persisted) application or user data with the need of changing it in time for computational needs.
We cannot use temporary variables to store changeable values, such as the total of an invoice. We cannot use an index to jump around a collection or an array, and we cannot iterate it. Obviously, if we need to write a function that needs a variable, we cannot use a variable anymore; in other words, we can't use variables that act as a business logic state persistence.
When we write a function, the data will simply have an origin, a target, and one or multiple transformations in multiple stages.
Thanks to this stateless design of the whole application, it is easy to see that each stage can run on a different thread together and each input or output endpoint can run on another thread and so on. The stateless design is the key that makes the design able to scale out quite perfectly according to Amdahl's Law.
As well as performance results, a stateless design brings higher testability rates of the whole application (bear in mind ASP.NET WebForms versus ASP.NET MVC) together with a more modern approach in programming style that avoids the use of interactive loops such as for, for...each, and relatives.
The last evolution of the imperative programming paradigm is object-oriented programming. Such paradigms request we model our business world into a high-level domain model. This means that, in our code, we will find an object representing any living entity of our business model; a invoice or a customer are examples of such objects. Such models drive business logic. They do not need to be persisted in a one-to-one representation from the model to the persistence store (usually, a relational database). This approach is called domain-driven design. The opposite of such an approach is the data-driven design that makes direct actions against data without a real discrimination between data and business.
Because of the intrinsic behavior of dataflow programming, a data-driven design is the natural choice when designing a solution based on such programing paradigms.
But in the modern .NET-based programming style, the use of business-related entities in the various stages of the dataflow execution is available and suggested too.
A data stream is the flow of some data in time, usually of a unique format, that is available to one or multiple readers.
Examples are television video streams, YouTube video streams, Twitter or RSS feeds, Azure EventHub, and so on. Those who are used to C# programming will remember the namespace System.IO that contains different classes made for stream programming, such as BinaryReader/BinaryWriter that makes available streaming any CLR low-level type or StreamReader/StreamWriter that makes available streaming any text supporting various encodings from ASCII to UTF32.
In other words, a data stream is some data in a specific time instance. Time is the key concept for understanding a data stream. It is all about running data or in-move data. Without the time component, data can never flow in a stream.
Depending on the stream, it may support seeking operations, such as the ability to go forward and backward along the stream to start flowing data exactly at the desired time. Television video streams do not support such a feature. Microsoft Azure EventHub (a data stream) instead supports the feature in a configured time window of usually some hours.
The Azure EventHub is a paralleled stream service for streaming any data, usually used for Internet of Things (IoT) devices, telemetry values, or diagnostic purposes as an application insights collection. A similar choice within the Azure offering is the IoT Hub, another streamed service totally oriented to IoT devices that support more specific protocols.
The Observer pattern, is a published subscribe style pattern; it defines the ability to register for data change or event signaling. Although written words may be something new to read about, the observer pattern is something absolutely overused in the event-driven programming paradigm of the Microsoft oriented languages in the last 20 years.
When we handle the Button click event, either in Visual Basic (from version 1 to 6) or in modern .NET Windows Forms, WPF applications, or even ASP.NET applications, we are simply using an implementation of the observer pattern.
The pattern defines an event generator, also known as subject, that fires the event and one or multiple event listeners or observers (in .NET, also known as event handlers) that will do something in reaction to the data state change or event signaling.
When dealing with data flow programming, the observer pattern is the one responsible for the acknowledgment between stages of the new data available. Each stage informs the following stages of new data available with a signal. Stages do not know about the overall design of the digraph. They simple signal the new data availability event; all subsequent stages that are observing the previous one for new data will be then acknowledged. This design makes useless the need of an overall data state, thus the design is stateless. Each stage observes or is being observed. That is all. Such data flowing between stages are data streams.