Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Reactive Programming for .NET Developers
Reactive Programming for .NET Developers

Reactive Programming for .NET Developers: Get up and running with reactive programming paradigms to build fast, concurrent, and powerful applications

eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Reactive Programming for .NET Developers

Chapter 2. Reactive Programming with C#

In the previous chapter, we gave an overall introduction to reactive programming and related languages and frameworks.

In this chapter, we will see a practical example of reactive programming with pure C# coding.

The following topics will be discussed here:

  • IObserver interface
  • IObservable interface
  • Subscription life cycle
  • Sourcing events
  • Filtering events
  • Correlating events
  • Sourcing from CLR streams
  • Sourcing from CLR enumerables

IObserver interface

This core level interface is available within the Base Class Library (BCL) of .NET 4.0 and is available for the older 3.5 as an add-on.

The use is pretty simple and the goal is to provide a standard way of handling the most basic features of any reactive message consumer.

As already seen in the previous chapter, reactive messages flow by a producer and a consumer and subscribe for some messages. The IObserver C# interface is available to construct message receivers that comply with the reactive programming layout by implementing the three main message-oriented events: a message received, an error received, and a task completed message.

The IObserver interface has the following sign and description:

    // Summary: 
    //     Provides a mechanism for receiving push-based notifications. 
    // 
    // Type parameters: 
    //   T: 
    //     The object that provides notification information.This type parameter is 
    //     contravariant. That is, you can use either the...

IObservable interface

The IObservable interface, the opposite of the IObserver interface, has the task of handling message production and the observer subscription. It routes right messages to the OnNext message handler and errors to the OnError message handler. As its life cycle ends, it acknowledges all the observers on the OnComplete message handler.

To create a valid reactive observable interface, we must write something that is not locking against user input or any other external system input data. The observable object acts as an infinite message generator, something like an infinite enumerable of messages; although in such cases, there is no enumeration.

Once a new message is available somehow, observer routes it to all the subscribers.

In the following example, we will try creating a console application to ask the user for an integer number and then route such a number to all the subscribers. Otherwise, if the given input is not a number, an error will be routed to all the subscribers...

Subscription life cycle

What will happen if we want to stop a single observer from receiving messages from the observable event source? If we change the program Main from the preceding example to the following one, we could experience a wrong observer life cycle design. Here's the code:

//this is the message observable responsible of producing messages 
using (var observer = new ConsoleIntegerProducer()) 
//those are the message observer that consume messages 
using (var consumer1 = observer.Subscribe(new IntegerConsumer(2))) 
using (var consumer2 = observer.Subscribe(new IntegerConsumer(3))) 
{ 
    using (var consumer3 = observer.Subscribe(new IntegerConsumer(5))) 
    { 
        //internal lifecycle 
    } 
 
    observer.Wait(); 
} 
 
Console.WriteLine("END"); 
Console.ReadLine(); 

Here is the result in the output console:

Subscription life cycle

The third observer unable to catch value messages

By using the using construct method, we should stop the life cycle of the consumer object. However...

Sourcing events

Sourcing events is the ability to obtain from a particular source where few useful events are usable in reactive programming.

Tip

If you are searching for the EventSourcing pattern, take a look at Chapter 7, Advanced Techniques .

As already pointed out in the previous chapter, reactive programming is all about event message handling. Any event is a specific occurrence of some kind of handleable behavior of users or external systems. We can actually program event reactions in the most pleasant and productive way for reaching our software goals.

In the following example, we will see how to react to CLR events. In this specific case, we will handle filesystem events by using events from the System.IO.FileSystemWatcher class that gives us the ability to react to the filesystem's file changes without the need of making useless and resource-consuming polling queries against the file system status.

Here's the observer and observable implementation:

public sealed class NewFileSavedMessagePublisher...

IObserver interface


This core level interface is available within the Base Class Library (BCL) of .NET 4.0 and is available for the older 3.5 as an add-on.

The use is pretty simple and the goal is to provide a standard way of handling the most basic features of any reactive message consumer.

As already seen in the previous chapter, reactive messages flow by a producer and a consumer and subscribe for some messages. The IObserver C# interface is available to construct message receivers that comply with the reactive programming layout by implementing the three main message-oriented events: a message received, an error received, and a task completed message.

The IObserver interface has the following sign and description:

    // Summary: 
    //     Provides a mechanism for receiving push-based notifications. 
    // 
    // Type parameters: 
    //   T: 
    //     The object that provides notification information.This type parameter is 
    //     contravariant. That...

IObservable interface


The IObservable interface, the opposite of the IObserver interface, has the task of handling message production and the observer subscription. It routes right messages to the OnNext message handler and errors to the OnError message handler. As its life cycle ends, it acknowledges all the observers on the OnComplete message handler.

To create a valid reactive observable interface, we must write something that is not locking against user input or any other external system input data. The observable object acts as an infinite message generator, something like an infinite enumerable of messages; although in such cases, there is no enumeration.

Once a new message is available somehow, observer routes it to all the subscribers.

In the following example, we will try creating a console application to ask the user for an integer number and then route such a number to all the subscribers. Otherwise, if the given input is not a number, an error will be routed to all the subscribers...

Subscription life cycle


What will happen if we want to stop a single observer from receiving messages from the observable event source? If we change the program Main from the preceding example to the following one, we could experience a wrong observer life cycle design. Here's the code:

//this is the message observable responsible of producing messages 
using (var observer = new ConsoleIntegerProducer()) 
//those are the message observer that consume messages 
using (var consumer1 = observer.Subscribe(new IntegerConsumer(2))) 
using (var consumer2 = observer.Subscribe(new IntegerConsumer(3))) 
{ 
    using (var consumer3 = observer.Subscribe(new IntegerConsumer(5))) 
    { 
        //internal lifecycle 
    } 
 
    observer.Wait(); 
} 
 
Console.WriteLine("END"); 
Console.ReadLine(); 

Here is the result in the output console:

The third observer unable to catch value messages

By using the using construct method...

Sourcing events


Sourcing events is the ability to obtain from a particular source where few useful events are usable in reactive programming.

Tip

If you are searching for the EventSourcing pattern, take a look at Chapter 7, Advanced Techniques .

As already pointed out in the previous chapter, reactive programming is all about event message handling. Any event is a specific occurrence of some kind of handleable behavior of users or external systems. We can actually program event reactions in the most pleasant and productive way for reaching our software goals.

In the following example, we will see how to react to CLR events. In this specific case, we will handle filesystem events by using events from the System.IO.FileSystemWatcher class that gives us the ability to react to the filesystem's file changes without the need of making useless and resource-consuming polling queries against the file system status.

Here's the observer and observable implementation:

public sealed class NewFileSavedMessagePublisher...

Filtering events


As said in the previous section, it is time to alter message flow.

The observable interface has the task of producing messages, while conversely observer consumes such messages. To create a message filter, we need to create an object that is both a publisher and a subscriber together.

The implementation must take into consideration the filtering need and the message routing to underlying observers that subscribe to the filter observable object instead of the main one.

Here's an implementation of the filter:

/// <summary> 
/// The filtering observable/observer 
/// </summary> 
public sealed class StringMessageFilter : IObservable<string>, IObserver<string>, IDisposable 
{ 
    private readonly string filter; 
    public StringMessageFilter(string filter) 
    { 
        this.filter = filter; 
    } 
 
    //the observer collection 
    private readonly List<IObserver<string>> observerList...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Get to grips with the core design principles of reactive programming
  • Learn about Reactive Extensions for .NET through real-world examples
  • Improve your problem-solving ability by applying functional programming

Description

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.

Who is this book for?

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.

What you will learn

  • Create, manipulate, and aggregate sequences in a functional-way
  • Query observable data streams using standard LINQ query operators
  • Program reactive observers and observable collections with C#
  • Write concurrent programs with ease, scheduling actions on various workers
  • Debug, analyze, and instrument Rx functions
  • Integrate Rx with CLR events and custom scheduling
  • Learn Functional Reactive Programming with F#

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 29, 2016
Length: 276 pages
Edition : 1st
Language : English
ISBN-13 : 9781785888496
Vendor :
Microsoft
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jul 29, 2016
Length: 276 pages
Edition : 1st
Language : English
ISBN-13 : 9781785888496
Vendor :
Microsoft
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 136.97
JavaScript for .NET Developers
$54.99
Learning Node.js for .NET  Developers
$32.99
Reactive Programming for .NET Developers
$48.99
Total $ 136.97 Stars icon
Banner background image

Table of Contents

9 Chapters
1. First Steps Toward Reactive Programming Chevron down icon Chevron up icon
2. Reactive Programming with C# Chevron down icon Chevron up icon
3. Reactive Extension Programming Chevron down icon Chevron up icon
4. Observable Sequence Programming Chevron down icon Chevron up icon
5. Debugging Reactive Extensions Chevron down icon Chevron up icon
6. CLR Integration and Scheduling Chevron down icon Chevron up icon
7. Advanced Techniques Chevron down icon Chevron up icon
8. F# and Functional Reactive Programming Chevron down icon Chevron up icon
9. Advanced FRP and Best Practices Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(2 Ratings)
5 star 50%
4 star 0%
3 star 50%
2 star 0%
1 star 0%
eros costas verde Oct 24, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
alot resources about Rx, this book make me open my mind to a new style of programming
Amazon Verified review Amazon
Craig E. Shea Aug 12, 2016
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
The biggest issue I have with the book is the editor did a really bad job. The authors (I know at least one of them for sure) is not a native English-speaking author. I have no issue with that--the authors' primary speaking language is what it is. However, if the book is going to be published in the English language, the editor ought to make sure that the sentences are grammatically and idiomatically correct for an English language reading audience.That is the primary job of the editor.Thank you Antonio for writing the book. Too bad the editor(s) did a very poor job of translating your thoughts to the English language in way that would make this much easier to comprehend.As far as content, the first half of the book focuses on core concepts. However, the details are nothing you probably couldn't pick up by reading the documentation. I haven't gotten to the second-half yet (it's a quick read--I just started reading this today); so when I finish the book, I'll come back and update this review to include more info on the second hald.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.