ReactiveUI goodies – Observing Properties

I have decided to start a new series of blog posts about practical programming. The goal of this series is to share some useful tools, coding practice and patterns I discover in my daily life of programming. Not only for you but for my future self. Who does not find answers in his own blog posts? Smile  As random as this series will be, I begin with this post.

In one of my current projects we use a ReactiveUI as the MVVM framework of choice. ReactiveUI has been around for a while and is based on the Reactive Extensions Rx. I will not give a full introduction to those frameworks, but you can read more about Rx and ReactiveUI at https://rx.codeplex.com/ and http://reactiveui.net/.

So before we get started we need to install ReactivUI. Luckily we live in a world of Nuget. So this is the only thing you need to do after opening the Nuget Package Manager Console:

PM> install-package reactiveui

Btw, ReactiveUI is available for Xamarin.iOS, Xamarin.Android, Xamarin.Mac, Xamarin Forms, WPF, Windows Forms, Windows Phone 8, Windows Store and Universal Windows Platform (UWP). Not bad.

The Problem

So what’s the problem we wanna solve?  Quite often its necessary to listen to changes of an objects property or multiple properties, such as ViewModels or any other object that implements INotifyPropertyChanged (INPC) for that matter. A common scenario is where you would like to trigger actions that are not (easily) possible via conventional DataBinding. E.g. customizing and starting storyboards or animations.

What WE usually do

The usual approach for this would be to subscribe to the property changed event provided by the INotifyPropertyChanged (INPC) interface.  Within the event handler you have to check for the property of interest. Before the “nameof” keyword we had to use reflection tricks or live with the danger of a magic string to check for the property name. This is what it would be like if you write it today without ReactiveUI.

ViewModel.PropertyChanged += ViewModel_PropertyChanged;
private void ViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    if (e.PropertyName == nameof(ViewModel.Foo))
    {
        // Do what you need to do with MainViewModel.Foo
    }
}

What you can do with ReactiveUI

With Rx you can subscribe to event streams similar to the previous event handler but in a much nicer way. So this is how it looks like with ReactiveUI.

ViewModel.WhenAnyValue(x => x.Foo)
    .Subscribe(foo =>
{
    // Do what you need to do with MainViewModel.Foo
    Debug.WriteLine($"Foo is: {foo}");
});

The WhenAnyValue extension comes as part of ReactiveUI and allows you to observe a property of any object. Of course it can only be notified if the class of the object implements INPC. As you can see everything is type safe and the code paths stay in one place, unlike the event handler. Now comes the cool part. Since IObservable, which is a fundamental type of all reactive programming, supports Linq, we can easily query to just a particular value of Foo.

ViewModel.WhenAnyValue(x => x.Foo)
     .Where(x => x == 14)
     .Subscribe(foo =>
 {
     // Do what you need to do with MainViewModel.Foo
     Debug.WriteLine($"Foo is: {foo}");
 });

Now what about observing multiple properties? No problem. The WhenAny extension does the trick.

ViewModel.WhenAny(x => x.Foo, x => x.Bar, (f, b) => new Tuple<int, string>(f.Value, b.Value))
    .Subscribe(values =>
       {
           Debug.WriteLine($"Values are: Foo:  {values.Item1}, Bar: {values.Item2}");
       });

As you can see, WhenAny can listen to multiple property changes and project the changed values into a new object. In my example I create a Tuple to hold the values. In the subscription handler you can evaluate the result.

I hope this little code example helps to make your future code a bit better and efficient. ReactiveUI holds many more gems you can utilize. But it’s also a whole new world with a steep learning curve. I will post more examples on ReactiveUI you can cherry pick and slowly dive into reactive programming.

All code for my practical coding series will be available on GitHub https://github.com/bitdisaster/practicalcode

Happy Coding!

2 thoughts on “ReactiveUI goodies – Observing Properties

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s