F#26 : Reactive Programming

In this post we will look at using a reactive programming paradigm within F#. There may be some of you that have used the Reactive Extensions (Rx), I am in fact a massive fan boy of Rx, and really enjoy what it can bring to a project, in particular I think a UI project benefits immensely from a more reactive approach.

There may of course be those of you that have never come across Rx at all. So lets take a very small detour and talk about the general idea of the observer pattern.

Observer Pattern

Lets say I have order system that should print invoices and also send emails to a client when a new order is received. A naive implementation of this may be to just lump all this into a single class, but this is a poor separation of concerns, we could do better. So what we could do, is to have a order system object which receives orders and then calls into 2 other classes that produce a invoice and send an email to a client.

This is ok, but we would now have to take a strong dependency on the 2 sub systems from the order system class, and then call them when a new order arrives. Wouldn’t it be better if the order system class could just accept a list of subscribers (say implementing some IAcceptOrder interface), and then any time a new order arrives the order system class would simply loop through its list of subscribers and call their AcceptOrder method (from the hypothetical IAcceptOrder interface).

This is essence is the observer pattern, of course this pattern could also allow unsubscribing too.

Rx has built upon the general idea of the observer pattern, and has added a great many standard .NET classes that aid in the construction of observable streams of data. You can also use subscriptions over events, asynchronous operations, and also use the standard LINQ operators.

This article is however about F#, so we will be keeping the discussion from here on out about the F# Observable modules.

Observable Module

The F# Observable module is the place to start for reactive programming in F#, and contains the following functions/types

We will be seeing some examples of these is just a minute, but before we do it is worth just going on another slight detour. So lets just get the slight detour over with before we start to look at the Observable module in depth.

<SlightDetour>

There were several things that made Rx so powerful :

The ability to treat events as a source to create an IObservable<T>. This IObservable<T> could then have any of the standard LINQ operators applied to it, along with another specific set of IObservable<T> extension methods. This is a very powerful technique, which allows you to do things like only listen to an event where some condition is true, project the original event args into a completely new type, merge 2 or more events into a single stream (this technique is particularly powerful when building UIs, I use this one a lot)

The decoupling of the event into a much for general purpose interface (IObservable<T>), which means that users of the original event source dino longer need a direct link to the original event source class (which they would do if they wanted to add an event handler to the source object event). Depending on a abstraction, i.e IObservable<T> is a much better / cleaner design. IObservable<T> is a base class type that is included in the .NET framework

The ability to subscribe, which would return a IDisposable, which you could then just wrap in a using(..) or Dispose of when you were done with it, both of which would stop the subscriber from receiving any further notifications

The F# team (Don Syme I guess here), have exposed some (though not all) of the Rx goodness in F# so it is important to understand some of the reasons why IObservable<T> is so useful.

</SlightDetour>

OK now that we have talked about why IObservable is better than a plain old event, lets have a look at some examples using the F# Observable module. Here is a small windows form (yes you can do forms in F# quite easily too) example that demonstrates the following things:

How to create an IObservable<’a> from a standard event using Observable.filter, where the filter is just being used to give back a IObservable<’a>, in essence no filtering at all

How to use Observable.add to add a handler to an IObservable<’a>

How to create an actual filter from an IObservable<’a> using Observable.filter, this filter ensures that only MouseMove events that happen in the bottom 1/2 of the form notify listeners

How to create an IDisposable subscription using Observable.subscribe

How to cancel a subscription by simply calling Dispose on the subscriber which is an IDisposable. In this example this is done using a Task.Delay(4000), which means the subscriber will only work for 4 seconds, and then will not receive any notifications after that

With this one I urge you to try the code out for yourself, as you will not be able to see that the Label2 associated TextBox stops updating after 4 seconds in a screen shot

This is cool for sure, but the real power of IObservable is that you can use it against your own events/properties too, so lets wrap up this post by looking at an example where we create our own event source, and look at a few more of the Observable module functions.

Here is a small class that contains a single “NewOrderEvent”, which uses a custom EventArgs derived class called “OrderEventArgs”. The “OrderEventArgs” has the following 2 properties:

//this will not fire any code, as we have filtered out to not include CEO EventArgsorderSystem.CreateOrder( { Price = 240.0m; AuthorisationLevel = Ceo } )

Console.ReadLine() |> ignore

//return 0 for main method0

There are several things to point out in this code:

We use a proper Observable.filter this time, such that only “Standard” and “Manager” AuthorisationLevel OrderEventArgs come through the applied filter. This means any event that has OrderEventArgs with a AuthorisationLevel of “Ceo” are effectively ignored thanks to the Observable.filter

We use Observable.partition to partition the source IObservable<OrderEventArgs> into 2 separate IObservable<OrderEventArgs> , one stream for Standard AuthorisationLevel and one stream for Manager AuthorisationLevel. When I say stream I really mean IObservable<T>

Here is what this code looks like when it is run:

Using More Of The Rx Extension Methods

As I previously stated, I am a massive Rx fan boy, so I was a little disappointed to see that the F# Observable module did not have the full set of extension methods that Rx would have for IObservable<T>. However it seems I am not alone here, and some people have put out a Github project which brings the standard Rx extension methods to F#, here is a link : https://github.com/fsprojects/FSharp.Reactive