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).
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");
}
}
Interview with XAMLCast about ReactiveXaml
Awhile back I did an interview with XAMLCast about the philosophy behind ReactiveXaml and basically what the library is about. If you’ve got the time between checking out all the great PDC10 videos, check this out as well:
ReactiveXaml Series: Displaying a ‘Loading…’ value
Some folks from the nRoute Framework were looking for an elegant way to handle displaying an intermediate value during async updates – something like changing the text to say “Working…” until the task is complete, then displaying the results. I realized this was pretty easy to do with ReactiveXaml, so I wrote up some code – here it is:
{
//
// Standard way in RxXaml to declare a notification-enabled property
//
string _InputData;
public string InputData {
get { return _InputData; }
set { this.RaiseAndSetIfChanged(x => x.InputData, value); }
}
// Our ICommand – invoking this will *begin* the async operation
ReactiveAsyncCommand DoubleTheString;
//
// OAPH will create an ‘output’ property – that is, a property who will
// be updated via an IObservable
//
ObservableAsPropertyHelper[string] _OutputData;
public string OutputData {
get { return _OutputData.Value; }
}
public CoolViewModel(Window MainWindow)
{
DoubleTheString = new ReactiveAsyncCommand(null, 1/*at a time*/);
IObservable[string] doubled_strings = DoubleTheString.RegisterAsyncFunc(x => {
// Pretend to be a slow function
Thread.Sleep(1000);
return String.Format("{0}{0}", x);
});
//
// ReactiveAsyncCommand will fire its OnNext when the command is *invoked*,
// and doubled_strings will fire when the command *completes* – let’s use
// this to our advantage:
//
IObservable[string] result_or_loading = Observable.Merge(
DoubleTheString.Select(x => "Loading…"),
doubled_strings
);
// Hook up our new ‘result_or_loading’ to the output
_OutputData = this.ObservableToProperty(result_or_loading, x => x.OutputData);
}
}

