Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting prior value on change of property using ReactiveUI in WPF MVVM

Tags:

c#

wpf

reactiveui

I'm using Reactive UI for an MVVM WPF project, and when a property changes I need to know:

  1. The value prior to change
  2. The new value (i.e. the change)

I have a viewmodel (Deriving from ReactiveObject) with a property declared on it such:

private AccountHolderType _accountHolderType;
public AccountHolderType AccountHolderType
{
   get { return _accountHolderType; }
   set { this.RaiseAndSetIfChanged(ref _accountHolderType, value); }
}

In the constructor I'm trying to do the following:

this.WhenAnyValue(vm => vm.AccountHolderType)
   .Subscribe((old,curr) => { // DO SOMETHING HERE });

but the WhenAnyValue method doesn't have such an overload, and the Reactive documentation is quite lacking.

I can gain access to a simple WhenAnyValue such that:

this.WhenAnyValue(vm => vm.AccountHolderType)
   .Subscribe(val => { // DO SOMETHING HERE });

this lets me observe the changes and get the latest change, but I need access to the prior value.

I'm aware I could implement this as a simple property such that:

public AccountHolderType AccountHolderType
{
   get { // }
   set
   {
      var prev = _accountHolderType;
      _accountHolderType = value;

      // Do the work with the old and new value
      DoSomething(prev, value);
   }
}

but given the project is using Reactive UI I want to be as "reactive-y" as possible.

like image 235
Clint Avatar asked Mar 17 '15 13:03

Clint


2 Answers

How about this:

 this.WhenAnyValue(vm => vm.AccountHolderType)
      .Buffer(2, 1)
      .Select(b => (Previous: b[0], Current: b[1]))
      .Subscribe(t => { 
//Logic using previous and new value for AccountHolderType 
});

I think you have missed this straight forward Buffer function.

like image 172
Kuroro Avatar answered Sep 21 '22 16:09

Kuroro


Something like:

var previousValue = this.WhenAnyValue(vm => vm.AccountHolderType);
var currentValue = previousValue.Skip(1);
var previousWithCurrent = 
  previousValue.Zip(currentValue, (prev, curr) => { /* DO SOMETHING HERE */ });
like image 29
Kent Boogaart Avatar answered Sep 20 '22 16:09

Kent Boogaart