9

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.

Clint
  • 6,133
  • 2
  • 27
  • 48

2 Answers2

19

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.

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
Kuroro
  • 1,841
  • 1
  • 19
  • 32
2

Something like:

var previousValue = this.WhenAnyValue(vm => vm.AccountHolderType);
var currentValue = previousValue.Skip(1);
var previousWithCurrent = 
  previousValue.Zip(currentValue, (prev, curr) => { /* DO SOMETHING HERE */ });
Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393