WhenAny / ObservableForProperty 如何访问以前的值和新值?

WhenAny / ObservableForProperty how to access previous and new value?

简单案例:

public class Foo : ReactiveObject
{
    public Foo()
    {
        this.ObservableForProperty(t => t.Bar, t => t).Subscribe(t =>
        {
            //Logic using previous and new value for Bar
        }
    }

    private int _bar;
    public int Bar
    {
        get { return _bar; }
        set { this.RaiseAndSetIfChanged(ref _bar, value); }
    }
}

在 ObservableForProperty 订阅中,只能访问 Bar 的新值(通过 t)。我们可以为 "beforeChange" 参数调用带有 true 的 ObservableForProperty,而不是只有以前的值而不是新的。

我知道我可以将我的代码逻辑插入 属性 setter,但我想保留 ObservableForProperty 行为(过滤第一个 setter 和当值不变)。 属性 也用于 XAML 绑定并需要 属性Changed 触发器。

我错过了什么吗?我怎样才能轻松做到这一点?谢谢

这样的事情怎么样:

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

请注意,这不会在您第一次更改栏时触发订阅逻辑。为了获得该功能,请在缓冲之前添加 .StartWith(this.Bar)

这在重叠模式下使用 Buffer 运算符 (skip < count)。