ReactiveUI: Is it All or None?
No! RxUI provides all of the core components that you need to use the M-V-VM pattern, but many people already have applications written using some of the other great .NET MVVM frameworks, such as MVVM Light or Caliburn.Micro – rewriting an entire codebase just to use Rx is a total bummer.
Fortunately, in ReactiveUI 2.2, there have been several features introduced in order to make using RxUI with existing frameworks easier – you can try out RxUI on a per-page basis, instead of rewriting your whole app.
There are really three core bits that are central to MVVM: a ViewModel object, an ICommand implementation, and a change-notifying Collection. Let’s take a look at how we can Rx’ify these three items.
Using MVVM Light alongside ReactiveUI
First, File->New Project and create a new “MVVM Light” projects via the template. Then via NuGet (you are using NuGet, right?), add a reference to the “ReactiveUI” project. Now, crack open MainViewModel.cs. The critical thing to know is, all of RxUI’s awesomeness are extensions onto an interface called IReactiveNotifyPropertyChanged. Ergo, we need to make MainViewModel implement this. But don’t panic, it’s easy!
Step 1: Change the class definition to implement IReactiveNotifyPropertyChanged.
Step 2: Add a field of type “MakeObjectReactiveHelper”, and initialize it in the constructor:
_reactiveHelper = new MakeObjectReactiveHelper(this);
/* More stuff */
Step 3: Paste in the following code at the end of your class, which just uses _reactiveHelper to implement the entire interface:
An important caveat about MakeObjectReactiveHelper
One thing that probably won’t affect you, but it might: MakeObjectReactiveHelper doesn’t properly completely implement IReactiveNotifyPropertyChanged unless you are also implementing INotifyPropertyChanging – most ViewModel implementations don’t (in fact, the interface doesn’t even exist in Silverlight or WP7). This means that in certain circumstances when you use the WhenAny or ObservableForProperty with a deep path (i.e. x.Foo.Bar.Baz), you may get duplicate notifications. In practice, this usually isn’t a big deal.
Watching ObservableCollections to create ViewModel collections
With RxUI 2.2, you can easily create a collection which tracks an existing collection, even if the source is an ObservableCollection. Here’s the syntax:
Creating ReactiveCommands like RelayCommands
Unfortunately, the story for ICommand isn’t as easy, you have to wrap commands one-at-a-time in order to subscribe to them. Here’s how to do it:
return ReactiveCommand.Create(cmd.CanExecute, cmd.Execute);