Getting a preliminary value when changing a property using ReactiveUI in WPF MVVM

I am using Reactive UI for an MVVM MVP project, and when I need to change a property, I should know:

  • Value before change
  • New value (i.e. change)

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

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

In the constructor, I am trying to do the following:

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

but the method WhenAnyValuedoes not have this overload, and the Reactive documentation is completely lacking.

I can access the simple WhenAnyValueso that:

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

this allows me to watch the changes and get the latest changes, but I need access to the previous value.

I know that I could implement this as a simple property so that:

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

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

, Reactive UI, "-y".

+4
2

:

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

, Buffer.

+5

- :

var previousValue = this.WhenAnyValue(vm => vm.AccountHolderType);
var currentValue = previousValue.Skip(1);
var previousWithCurrent = previousValue.Zip(currentValue, (prev, curr) => { /* DO SOMETHING HERE */ });
+1

All Articles