Reactive UI: Doing It Better

I thought I had the hang of ReactiveUI, but when I got told I was Doing It WrongTM I took the opportunity to reconsider how I might start Doing It Better.

Never write anything in the setter in ReactiveUI other than RaiseAndSetIfChanged – if you are, you’re definitely Doing It Wrong™Paul Betts

With that in mind I wondered how how I might acheive that. Firstly its going to make all my properties much simpler, in fact my initial thought was how to wire up a ViewModel property back to its model property if I can’t use the property. In the past I would have previously used

// This is wrong
public bool IsSet 
{
    get { return _model.IsSet; }
    set 
    { 
        this.RaisePropertyChanging(x=>x.IsSet);
        _model.IsSet = value;
        this.RaisePropertyChanged(x=>x.IsSet; 
    }
}

However that’s not very observable. So if instead we stick with the idea of making the property only do the notification, then we need something to update the model property on the view model change. Well that sounds just like an observable to me.

public bool IsSet 
{ 
    get { return _IsSet; } 
    set { this.RaiseAndSetIfChanged(x => x.IsSet, value); } 
}

and in the constructor

this.ObservableForProperty(x=>x.IsSet).Subscribe(x=>_model.IsSet);

Now we have a building block that enables us to build up the complicated functionality that we need.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

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