Stop What You Are Doing And Learn About Reactive Programming

Windows Phone From Scratch #26

I’m increasingly convinced that Reactive Programming is going to be critical for Silverlight and Windows Phone developers.  Reactive Programming is not new, and the Rx toolkit has been out for a while, but this is not a heavily covered topic, and the more I look the more I think it should must be.

In short, Reactive Programming is a way to take aspects of your code that are currently imperative and turn them into something much more event-driven.  In fact, Reactive Programming is sometimes referred to as LINQ Over Events.

This is tremendously helpful with asynchronous programming, but also with managing routine programming as well.

Let me start by acknowledging some of the foundation videos that are already available for Reactive Programming, including

To get our feet wet, let’s create a very first program with the Reactive Programming Extensions (you want Rx for Silverlight 4).  What I’m about to demonstrate is not original; the idea has been used in other folk’s examples and I’m grateful to them all.

Enumeration Vs. Observation

Much of Reactive Programming turns on the idea of an Observable Collection vs. a simple enumerable collection. For example, to extract data from a collection and add it to a list box you would traditionally iterate through the list box, extracting each objectg in turn and add it to the list box.

In Reactive Programming you are informed about each object in turn (think of this as push as opposed to pull!) and you may react to each notification however you like, for example you might add the pushed object to a list box.

An example makes this much clearer.  Create a new Windows Phone project and on the first page divide the Content panel into two columns.  Place a list box in each of the two columns, naming the first lbEnumerable and the second lbObservable.

We need some data so let’s initialize a List<string> with the names of the first five presidents:

 readonly List<string> names = new List<string>
 {
    "George Washington",
    "John Adams",
    "Thomas Jefferson",
    "James Madison",
    "James Monroe",
    "John Quincy Adams"
 };

This member variable will be the source for populating both list boxes.  We’ll do all of the work in a method called PopulateCollection() that we’ll call from the constructor.

In the first part of PopulateCollection() we’ll take the traditional approach and iterate through each member of the collection, adding each president’s name to the list box,

 private void PopulateCollection()
 {
    foreach ( string pName in names )
    {
       lbEnumerable.Items.Add( pName );
    }

That works great, but it is possible that you won’t have the entire collection at your fingertips; rather you may be provided with each individual name one by one based on events whose timing you may not control.  Reactive programming solves that problem for you.  You can simulate this by converting the list<string> to an observable collection (that is, a collection that implements IObservable).

To do this, first ensure that you have added System.Core.Ex, Microsoft.Phone.Reactive and System.Observable to your references.  Then use the ToObservable() extension method on your List of names to create an instance of an IObservable collection,

IObservable<string> observable = names.ToObservable();

The subscribe method of an observable collection is overloaded.  The first parameter you can pass in is of type Action<T> which subscribes a value handler to an observable sequence.  Again, the code makes this clearer,

observable.Subscribe<string>
(
   pName =>
   {
      lbObservable.Items.Add( pName );
   }
);

The highlighted code is the body of the Action<T> which in this case is a Lambda expression indicating that given a string pName the body of the “method” adds that name to the appropriate list box.

I will return to Rx frequently in coming days and we’ll tackle some more complex examples as we go.

The key question that has to be answered, and to which I honestly don’t yet know the answer, is this:  Is Reactive Programming going to become central to Windows Phone Programming, or will it remain an esoteric and peripheral approach?

For context, here is the complete program:

using System;
using System.Collections.Generic;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Reactive;

namespace Rx1
{
   public partial class MainPage :
      PhoneApplicationPage
   {

      readonly List<string> names =
         new List<string>
      {
         "George Washington",
         "John Adams",
         "Thomas Jefferson",
         "James Madison",
         "James Monroe",
         "John Quincy Adams"
      };

      public MainPage()
      {
         InitializeComponent();
         PopulateCollection();
      }

      private void PopulateCollection()
      {
         foreach ( string pName in names )
         {
            lbEnumerable.Items.Add( pName );
         }

         IObservable<string> observable =
            names.ToObservable();

         observable.Subscribe<string>
         (
            pName =>
            {
               lbObservable.Items.Add( pName );
            }
         );
      }
   }
}

Special Thanks to Pencho Popadyn whose demonstration program was the basis for my example.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in Patterns & Skills. Bookmark the permalink.