Reader small image

You're reading from  .NET Design Patterns

Product typeBook
Published inJan 2017
Reading LevelIntermediate
PublisherPackt
ISBN-139781786466150
Edition1st Edition
Languages
Tools
Right arrow
Authors (2):
Praseed Pai
Praseed Pai
author image
Praseed Pai

Praseed Pai has been working in the software industry for the last 25 years, starting his career as a MS-DOS systems programmer using ANSI C. He has been actively involved in developing large-scale, cross-platform, native code-based systems using C++ on Windows, GNU Linux, and macOS X. He has experience in COM+ and CORBA programming using C++. In the last decade, he has worked with Java- and .NET-based systems. He is the primary implementer of the SLANG4.net compilation system, which has been ported to C++ with an LLVM backend. He coauthored .NET Design Patterns, by Packt Publishing.
Read more about Praseed Pai

Shine Xavier
Shine Xavier
author image
Shine Xavier

Shine Xavier is a core software engineering practitioner with an extreme passion for designing/building software solutions, application frameworks, and accelerators that help maintain productivity, code quality, performance, and security. His areas of interest include functional programming, interpreters, JavaScript library development, visual programming, algorithms, performance engineering, automation, enterprise mobility, IoT and machine learning. He is currently associated with UST Global as a senior architect, where he continues to provide technical leadership in customer engagements, pre-sales, practice development, product development, innovation, and technology adoption. He lives with his wife and three kids in Thiruvananthapuram, Kerala, India.
Read more about Shine Xavier

View More author details
Right arrow

Chapter 13. Reactive Programming Using RxJS

In the previous chapter, we saw how .NET Reactive Extensions (Rx) aided natural programming in terms of composability, scalability, and responsiveness. We saw how streams enable natural state management with respect to time. Some of the constructs were dealt with in detail as well. More importantly, we saw how reactive constructs could be integrated seamlessly into the MVVM pattern, in terms of achieving data synchronization between View and Model via the View Model layer. Now, in this chapter, we will take a deep dive into the Reactive Extensions for JavaScript (RxJS) library, and look at how to write asynchronous and event-driven programs using observable collections. We will also take a detailed look at some interesting use cases, and their implementations with RxJS, to clearly understand how the RxJS library is leveraged to create concurrent and responsive applications. This will cover the reactive spectrum of web and Windows programming and...

The JS world


It is important to recap one's understanding of some of the JavaScript world's state of affairs. The most important aspect is that the language is single-threaded and, given this, the only option left for developers to write asynchronous code is by using callbacks, promises, and events. As a developer, you should be comfortable with the functional programming aspects of JS (in addition to its innate dynamic nature), including closures, higher-order functions, anonymous functions, and extension methods (augmenting types). We also cannot discount the advancements that have been made in the language core itself, with Node.js now becoming a preferred backend for serious scalability involving async I/O. Let's have a quick peek into these core concepts before we dive into RxJS.

As we all know (we presume you do), functions are objects in JavaScript, and they are first-class citizens, which makes JS a functional programming language as well (although it is formally classified as a dynamic...

Rx foundations


Although it may sound repetitive, it is so important to understand the foundations of Rx and the key design patterns that govern Rx. Being a book on patterns and idioms, it would be really gratifying to know if any interested reader would benefit from understanding the underpinnings of these keys concepts as they are realized in the host language (JS in this case) directly or via libraries.

The two key design patterns based on which Rx works are the observer and iterator patterns. Let's have a quick look at how these patterns are implemented, and then speculate or peek at a possible implementation of RxJS. This way of learning would really help in forming a deeper understanding of the core concepts. And not to hide the fact that the authors themselves have attempted to create a JS library (code-named YieldJS on GitHub at http://shinexavier.github.io/YieldJS/), which gives the rudimentary capability of RxJS despite being a pull-based implementation. However, one thing to keep...

RxJS formalism


Now, unlike YieldJS, RxJS is push-based. Here, the subscribers would automatically receive new values from the publisher. A subscriber or listener is denoted by the observer object, and the publisher (that pushes/publishes new values) is denoted by the Observable object. Just like the way we specified iterator methods (our future operators) to compose our generated sequences, we can efficiently do the same (transform, filter, and so on) for all the elements in the observable sequence.

Observables and observers

The generator becomes our observable, and the callback function, which would be interested in these sequences, becomes the observer. Having said this, creating Observables is pretty straightforward, as we saw in the earlier chapter with reactive extensions for .NET. The following code bares it all:

    var client = Rx.Observable.create(function (observer) { 
      observer.onNext('On Your Mark'); 
      observer.onNext('Get Set'); 
      observer.onNext(...

RxJS samples


How can we even proceed without seeing our spell checker in action on a web page? For this, we need an ASP.NET Web API that provides the suggestions. We will reuse our earlier NorvigSpellCheckerModel class as-is for this:

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Net; 
    using System.Net.Http; 
    using System.Web.Http; 
    using SpellChecker; 
 
    namespace MvcApplication1.Controllers 
    { 
      public class SearchContext 
      { 
        public string Lookup { get; set; } 
        public int Count { get; set; } 
      } 
      public class ValuesController : ApiController 
      { 
        ISpellCheckerModel _spellChecker =      
        NorvigSpellCheckerModel.Instance; 
        // GET api/values 
        public IEnumerable<string> Get([FromUri] SearchContext      
        context) 
        {...

Summary


By now you must have understood how reactive programming is employed for modeling solutions the way the world exists. The principle has been applied for various mainstream programming languages, as thought leaders such as Erik Meijer found this too natural to express and compose. And we got lucky in this discovery process. We believe, as developers, you must have have started appreciating the world of functional and reactive programming beyond OOP. In the next chapter, we will be specifying, in brief, some important topics which could not be covered in the book, such as polyglot programming, domain specific languages (DSLs), ontology, and AntiPatterns.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
.NET Design Patterns
Published in: Jan 2017Publisher: PacktISBN-13: 9781786466150
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Praseed Pai

Praseed Pai has been working in the software industry for the last 25 years, starting his career as a MS-DOS systems programmer using ANSI C. He has been actively involved in developing large-scale, cross-platform, native code-based systems using C++ on Windows, GNU Linux, and macOS X. He has experience in COM+ and CORBA programming using C++. In the last decade, he has worked with Java- and .NET-based systems. He is the primary implementer of the SLANG4.net compilation system, which has been ported to C++ with an LLVM backend. He coauthored .NET Design Patterns, by Packt Publishing.
Read more about Praseed Pai

author image
Shine Xavier

Shine Xavier is a core software engineering practitioner with an extreme passion for designing/building software solutions, application frameworks, and accelerators that help maintain productivity, code quality, performance, and security. His areas of interest include functional programming, interpreters, JavaScript library development, visual programming, algorithms, performance engineering, automation, enterprise mobility, IoT and machine learning. He is currently associated with UST Global as a senior architect, where he continues to provide technical leadership in customer engagements, pre-sales, practice development, product development, innovation, and technology adoption. He lives with his wife and three kids in Thiruvananthapuram, Kerala, India.
Read more about Shine Xavier