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

2

10

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.

Overburdensome answered 17/3, 2015 at 13:30 Comment(0)
C
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.

Crown answered 13/3, 2016 at 15:14 Comment(0)
T
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 */ });
Traffic answered 9/5, 2015 at 7:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.