ReactiveUI Link Roundup
If you’re new to ReactiveUI and you’re looking for information on how it works, I’ve written lots of blog posts on the topic. Here’s some of the best ones:
- Calling web services elegantly
- Implementing a Flickr Image Search
- ICommands in RxUI
- Easy async ICommands in RxUI
ReactiveUIPosts.Subscribe()
I make sure to post all of my RxUI-related posts under the Reactive Extensions category on my blog, and I also usually tweet about them via Twitter, my handle there is @xpaulbettsx.
Where can I get help?
If you’re trying out ReactiveUI and something doesn’t work right, or it’s not clear how to go about doing something, send me an Email. Another good place to get support is the ReactiveUI Google Group.
ReactiveXaml is now ReactiveUI 2.0!
What does ReactiveUI do?
ReactiveUI is a M-V-VM framework like MVVM Light or Caliburn.Micro, that is deeply integrated with the Reactive Extensions for .NET. This allows you to write code in your ViewModel that is far more elegant and terse when expressing complex stateful interactions, as well as much simpler handling of async operations. Check out this video for an overview:
Why the name change? I liked ReactiveXaml
The main reason I decided to change the name, is that many of the classes in ReactiveUI are useful outside of WPF and Silverlight, especially with a new library that I’m working on called ReactiveUI.Serialization (not quite ready yet!) Observable objects and collections are quite useful in non-XAML domains as well, so I want to broaden the scope a bit. For example, I think a lot of these classes could be pretty useful for building ASP.NET MVC ViewModels as well! I think ReactiveUI’s shortened name of RxUI looks better too
Where can I find the library?
On NuGet! The best way to install ReactiveUI for a project is by installing the ReactiveUI package for WPF/Silverlight projects, or ReactiveUI-WP7 for Windows Phone 7 projects.
If NuGet isn’t your thing, you can also find the binaries on the Github page: ReactiveUI 2.0.0.2.zip.
Where can I see a sample?
A sample project for WPF 4.0 that includes everything you need to see how it works is on the Github page: ReactiveUI 2.0 Sample.zip. It includes a small sample app, the RxUI binaries, and some sample test cases.
Version 2.0 means breaking changes
ReactiveUI uses semantic versioning (mostly), which means that version 2.0 contains breaking changes from the 1.x series. The biggest one is the namespace change and split – several classes that have dependencies on WPF/Silverlight are now moved into the “ReactiveUI.Xaml” assembly/namespace. Fixing this is usually pretty straightforward. Most of the other breaking changes are name changes and shuffling some parameter names around, especially in ReactiveCommand and ReactiveAsyncCommand.
Here’s one big change that is more subtle – in previous versions of ReactiveUI, the “Changed” Observable would give you “Sender”, “PropertyName”, and “Value”, but Value would be null on certain Observables and non-null on others, in a completely arbitrary way. In ReactiveUI 2.0, the rule is, if you explicitly ask for the property by-name (i.e. via ObservableForProperty), the Value will be set. However, there is also a GetValue() method on ObservedChange and a Value() method on IObservable
New features in 2.0
- ReactiveUI now has a simple, Rx-enabled Message Bus, inspired by MVVM Light’s Message Bus
- A new set of extension methods to help writing unit tests (ReactiveUI.Testing) – write unit tests that simulate concurrency without using Thread.Sleep, and get the same results every run
- Unit test detection now correctly works with Silverlight
- A new async cache class that supports Silverlight, and an extension method to easily integrate it to existing code (MemoizedSelectMany). Easily turn concurrent web calls into memoized, rate-throttled web calls
- Object validation is vastly improved in this release – many bugs fixed and is more performant.
- The same async cache class is also used in ReactiveAsyncCommand to properly support memoization
- CreateDerivedCollection() now works with ObservableCollection, making it easier to create ViewModels from existing non-RxUI code
- Easily get an Observable from a DependencyProperty (ObservableFromDP), even in Silverlight and WP7
- Cleaner syntax for creating properties based on Observables
- Intellisense documentation for all classes
- ReactiveCollection is vastly improved – it now supports tracking object property changes (i.e. it’s now easy to track “Tell me when items are added/removed, or when a property changes on any of the objects in this list”)
- RxUI now uses the latest Rx.NET release (the “Christmas Release”)
- The RxUI core DLL is no longer dependent on any WPF binaries, so it is more palatable to integrate into non-WPF projects.
Hey, why is this version 2.0.0.2
Here’s some advice to other developers – if you’re ever considering, “Oh, I’ll just change this one thing right before I release, it’ll be fine!”, don’t. Here’s the last-minute bug that I introduced that completely borks v2.0.0.0. :: sigh ::
https://github.com/xpaulbettsx/ReactiveUI/commit/b00354decf7c97e5af1148a6693136935fb82d22#L3L50
Building the project:
Building the project requires having quite a few products installed – to build a full release, you need:
- Visual Studio 2010
- Pex / Moles
- Code Contracts for .NET
- Expression Blend 4.0
- Silverlight 4.0 Development Tools
- Windows Phone 7 Development Tools
That being said, if you’re only interested in ReactiveUI core, you only need VS2010 Professional – the other projects can simply be unloaded. Clone the source from GitHub, or download the 2.0.0.2 source code release as a Zip file (though I highly recommend the former).
Lots of new stuff coming, but RxXaml is now in crazy experimental mode
If you’re tracking ReactiveXaml, you most likely don’t want to use the code that’s currently in master right now – you’ll want to stick with either the released version, or a commit earlier than c2a4o. In the meantime, here are the three things that I’m currently working on that are totally wreaking havoc on the tree:
- Using TestScheduler on tests, so that testing async commands happens instantly and 100% reliably, instead of using Thread.Sleep hacks
- A new MRU cache designed to replace QueuedAsyncMRUCache called ObservableAsyncMRUCache – it will be usable on Silverlight and WP7, and has much more usable behavior than the old class
Oh, and one more thing – porting a version of ReactiveXaml to MonoTouch. Write the same declarative code against iOS, use super-powered Key-Value Coding via Observable Bindings, and handle async code easily and gracefully.
Making Async I/O work for you, Reactive style
Earlier today, I read a fantastic article about the TPL by Scott Hanselman. In it, he describes how to take a fairly straightforward function to detect if a given Url responds, and write it in an asynchronous fashion. As soon as I read it, I knew that I had to write the Reactive Extensions for .NET version!
How do the TPL and Rx.NET relate?
Both of these technologies are intended to help make writing asynchronous and concurrent programs easier and more straightforward, so it’s really easy to be confused as to which one to use. You can often think of Task and IObservable for async calls as the same thing – an object that represents a future result that hasn’t completed yet – we saw this in a previous blog post. In an asynchronous function, we send out the request, but we don’t have the data – we have to return something that will allow us to eventually get the result.
When it comes down to it, Task is really a specialization of IObservable – Task is specifically designed to run on the TPL threadpool, whereas IObservable abstracts away where the code will execute unless you specify it explicitly.
Seeing the problem again
Let’s take a look at the synchronous version of the code again – we want to take this and rewrite it so that it doesn’t block:
Writing our initial stab at VerifyUrlAsync
Just like Scott’s Task-based async function, we’ll also define a function that returns a future result. However, instead of using Task as our return type, we’ll define a function that returns IObservable:
Now, let’s see the implementation:
How can we use this?
This method will not block, it will instantly return you an IObservable representing the future result. So, there are a couple of ways you can use the Observable to “unpack” the result:
Now, let’s see how we can do arrays:
The truly revolutionary thing about Rx.NET is how the same primitive you used in LINQ now take on awesome new meanings when applied to the domain of the future. So, the first thing we’ll do is take our array and convert it to an IObservable via AsObservable. This means that the resulting IObservable will produce n items, one for each element in the array, then OnComplete.
The natural thing we would do to get the result is someObservable.Select(x => ValidateUrlAsync(x)). However, there’s a problem – our type is now IObservable<IObservable<T>>; we now have a “future list of futures” (thinking of IObservable as a “future list” is a good analogy, whereas the web call is just a “future list” with only one item). We need a way to flatten down our future list back to IObservable<T> – so what’s the way to flatten a list in LINQ? SelectMany, of course! SelectMany is the secret behind writing async Rx code. Let’s see how to do it:
The code above is still asynchronous – at no time will we block, and it will instantly return. The SelectMany’s default IScheduler will run items on the TaskPool (actually in this case, we never used any synchronous method so we will never block, even on a Threadpool thread. To get the result, similar to the above method, we’d have to call First() on it.
If we were to dump the IObservables at every point of the computation, it’d look something like this:
[ "http://foo", "http://bar" ] ===>
[ {"http://foo", false}, {"http://bar", false} ] ===>
[ Dictionary ]
Cool! Where can I learn more?
- The Rx Hands-on-lab is an awesome, thorough, and technically correct introduction to Rx.NET
- The Rx.NET forums are full of really smart, helpful people – I’ve learned a ton by reading through the forum posts
- The Rx.NET videos on Channel 9 are a great resource – the developers behind the library itself explain the concepts in an easy-to-understand way
- My blog series on ReactiveXaml and Rx.NET is also a good way to understand many practical uses of Rx, especially if you’re writing desktop / Silverlight / WP7 apps.
Detecting whether your .NET library is running under a unit test runner
Here’s a piece of code that I found useful for ReactiveXaml, how to detect whether you are running under the unit test runner. For WPF/Silverlight testing, this is important to know since Dispatcher.Current exists but is bogus (i.e. none of the things you queue to it will run during the unit tests). The official version comes from here.
{
string[] test_assemblies = new[] {
"CSUNIT",
"NUNIT",
"XUNIT",
"MBUNIT",
"TESTDRIVEN",
"QUALITYTOOLS.TIPS.UNITTEST.ADAPTER",
"QUALITYTOOLS.UNITTESTING.SILVERLIGHT",
"PEX",
};
#if SILVERLIGHT
return Deployment.Current.Parts.Any(x =>
test_assemblies.Any(name => x.Source.ToUpperInvariant().Contains(name)));
#else
return AppDomain.CurrentDomain.GetAssemblies().Any(x =>
test_assemblies.Any(name => x.FullName.ToUpperInvariant().Contains(name)));
#endif
}
ReactiveXaml 1.4.1 Released
Last night, I was helping Jason Ward port the Flickr demo from my previous post to WP7, and I discovered a serious bug in the WP7 and Silverlight releases. While the code in the Github repository for 1.4 doesn’t have the issue, my binaries included some hack changes that I didn’t intend to be in the build.
The hard lesson for today is, always base your builds on a 100% clean working tree (and preferably automate them!). The good news is, that folks can get the Observable.CreateCollection extension method that I demoed in an official release now.
There’s also an easy workaround for the lazy / impatient – add this line to the top of your SL / WP7 application:
Check out Github in the Downloads section for the latest bits, I’ll also be updating NuGet when I have the chance.
ReactiveXaml Series: Using ReactiveCollection to improve the Flickr Search sample
One of the types in ReactiveXaml that is quite useful that I haven’t mentioned before on the blog is an extension of WPF/SL’s ObservableCollection (no relation to IObservable), called (predictably enough), ReactiveCollection. It works wherever you’d use an ObservableCollection in a traditional M-V-VM library, but it has a few useful tricks worth mentioning.
The basics, plus watching item change notifications
As you might imagine, ReactiveCollection adds the following IObservables that you can subscribe to:
- BeforeItemsAdded / ItemsAdded
- BeforeItemsRemoved / ItemsRemoved
- CollectionCountChanging / CollectionCountChanged
In addition to this, ReactiveCollection can also watch item change notifications on the items in the list, so you can express “Tell me when the collection itself changes, or any of its elements“. This can be expensive for large lists, so it is disabled by default – use the ChangeTrackingEnabled property to enable/disable it. As you add/remove items, ReactiveCollection will be subscribing/unsubscribing to the underlying objects.
Automatically creating ViewModel collections
Since we now have information easily exposed about when items are added/removed, it was fairly straightforward to create a Collection who automatically follows another Collection via a Selector, called “CreateDerivedCollection”. Here’s the most useful case:
var ViewModels = Models.CreateDerivedCollection(x => new ViewModelForModelClass(x));
// Now, adding / removing Models means we
// automatically have a corresponding ViewModel
Models.Add(new Model("Hello!"));
ViewModels.Count();
>>> 1
This really makes it easier follow the M-V-VM pattern properly when it comes to collections – the code is editing the Models, and these new Models are being projected into new ViewModels automatically.
Creating a collection from an Observable
A post-1.4 method called CreateCollection that I recently added will also allow you to create a list based on an Observable, optionally spacing each of the items apart by a certain amount of time. If the time is specified, the list returned is always empty, but slowly fills itself over time – this is great for populating Listboxes in a more lifelike way. We’ll see this in action in the sample.
Improving our Flickr search sample
In the sample for ObservableAsPropertyHelper, I showed how to implement a simple Flickr tag search. Using CreateCollection, we can make the tiles appear on a delay which looks snazzier.

Animations don’t show up well as images. Click to download the sample project with binaries.
Let’s take a look at what changed – first, we changed our output results from a List to a ReactiveCollection:
public ReactiveCollection[FlickrPhoto] Photos {
get { return _Photos.Value; }
}
Next, we update GetSearchResultsFromFlickr to provide a ReactiveCollection instead of a List, really only by changing the first and last lines:
{
/* [[[SNIP]]] This part is long and boring */
var ret = items.Zip(urls, (item, url) =>
{ item.Url = url; return item; }).ToList();
// Take the return list, convert it to an Observable,
// then create a collection who will initially be
// empty, but we’ll copy one item at a time every
// 250ms until we’ve copied everything from ret.
return ret.ToObservable().CreateCollection(TimeSpan.FromMilliseconds(250.0));
}
Making it even snazzier – adding the fade-in
Adding the items every 250ms is okay, but to really make this look great we need an animation to fire whenever an item is added. To do this, we override the ListBoxItemContainer template, and make these changes (this has nothing to do with ReactiveXaml directly, but it’s a cool trick nevertheless):
- Make a copy of the ListBoxItemContainer template
- Set the Border opacity to zero (its initial state)
- Create a Storyboard which will animate the opacity back to 100% in 1.5 seconds (using the Power easing function)
- Add an Expression Blend EventTrigger on the Loaded event, that will kick off our Storyboard
ReactiveXaml now in the NuGet main repository
ReactiveXaml is now in the CTP2 NuGet repository – for new projects, this is a great way to get started, not only with ReactiveXaml but with a lot of other great libraries, and it will also pull in the correct version of the Reactive Extensions for free.
Update: It is only in the CTP2 repository (you can see it if you take your favorite OData viewer and point it at http://feed.nupack.com/ctp2/odata/v1/), but you won’t be able to find it using CTP1, which is the previous release.
ReactiveXaml 1.4.0.0 is released, including samples and binaries
After resolving the Silverlight 4 issues, a new release is definitely in order. To that end, I present ReactiveXaml 1.4.0.0.
Remind me what ReactiveXaml is again?
ReactiveXaml is a M-V-VM framework like MVVM Light or Caliburn.Micro, that is deeply integrated with the Reactive Extensions for .NET. This allows you to write code in your ViewModel that is far more elegant and terse when expressing complex stateful interactions, as well as much simpler handling of async operations. Here’s some motivating posts that have more info:
- Video interview about ReactiveXaml
- Calling web services elegantly
- Implementing a Flickr Image Search
- ICommands in RxXaml
- Easy async ICommands in RxXaml
New features in 1.4
- Added Debug Mode, which will add extra logging and catch certain bugs early in your apps’ debug builds. Enable it by calling
RxApp.EnableDebugMode()inside an #if DEBUG block. - Most change notifying types (ReactiveObject, ReactiveCollection) now support the INotifyPropertyChanging interface, so you can be notified right before a property will change, as well. Corresponding IObservables have been added as well (i.e. “ItemsAdded” now has “BeforeItemsAdded” as well)
- Updated our copy of Rx to the PDC10 release
- Many bugs fixed, especially with SL4 and WP7
How can I get started quicker?
Download the binary release here (UPDATE: This release has a blocking issue for SL and WP7, 1.4.1 corrects this and I’ve updated the links here to point to that release instead):
- ReactiveXaml 1.4.1.0 for .NET 4 / .NET 3.5 / Silverlight 4 / Windows Phone 7
- ReactiveXaml 1.4.1 WPF Sample Project including RxXaml binaries
Building the project:
Building the project requires having quite a few products installed – to build a full release, you need:
- Visual Studio 2010
- Pex / Moles
- Code Contracts for .NET
- Expression Blend 4.0
- Silverlight 4.0 Development Tools
- Windows Phone 7 Development Tools
That being said, if you’re only interested in ReactiveXaml core, you only need VS2010 Professional – the other projects can simply be unloaded. Clone the source from GitHub, or download the 1.4.0.0 source code release as a Zip file (though I highly recommend the former).
Some annoying bugs to be aware of in ReactiveXaml for Silverlight
Despite ReactiveXaml being available for WPF, Silverlight, and Windows Phone 7, I have a confession to make: the vast majority of my use with this library is in WPF. The test suite runs under WPF, all of the applications that I am building to prototype RxXaml features are WPF applications, etc. This isn’t any slight against Silverlight, it just happens to be what I’m usually working on. So, I assumed naïvely that ReactiveXaml under SL4 would “just work”.
It works now, after some fixups
After some folks messaged me about some issues in the Silverlight version, I decided to wire up the SL test runner to see if I could reproduce some of these issues. Using a great test runner called StatLight, I could quickly see that there are some bugs. Luckily, we now run the SL unit test runner as part of the test suite, so hopefully this won’t be the case any more.
List of bugs fixed as of today
- ReactiveCollection failed any time someone called “coll[x] = foo”; this is because Silverlight’s ObservableCollection returns different results than the desktop CLR on NotifyCollectionChangedAction.Replace
- Any method involving Expression Trees failed, because SL’s Type.GetField doesn’t appear to return any results if you pass BindingFlags to it
- Notifications that were supposed to come in on the UI thread were coming in on other threads – this was a dumb typo on my part
Bugs that still need fixed
- To actually get the unit test runner to work, you have to rig this line to say “return true” – I haven’t yet figured out a way to determine whether we are in a unit test runner in Silverlight, since AppDomain.GetAssemblies() doesn’t exist, though I’ve got a good idea I’ll try soon.
An annoying caveat for SL4
On Silverlight 4, for security reasons, you cannot use Type.GetField to access private types – whereas protection on the desktop CLR is done at compile time, on SL4 this is enforced at run-time as well. This really sucks for RxXaml, since it uses reflection to set backing fields. The workaround is ugly, you have to mark your backing field as public, or use the simpler RaisePropertyChanged and write properties by-hand. So, here’s the way for SL4 to correctly write a read-write property:
public string _SearchText;
public string SearchText {
get { return _SearchText; }
set { this.RaiseAndSetIfChanged(x => x.SearchText, value); }
}
Alternatively, if the ‘public’ really annoys you, here’s how to do it by-hand:
public string SearchText {
get { return _SearchText; }
set {
if (_SearchText == value)
return;
_SearchText = value;
this.RaisePropertyChanged("SearchText");
}
}

