强制 WhenAnyValue 重新评估

Force WhenAnyValue to re-evaluate

是否有一种干净的方法来强制 WhenAnyValue 重新评估自身并为其订阅者调用 onNext?

    protected override IObservable<bool> IsDirty() {
        return this.WhenAnyValue 
        (x => x.Firstname,
         x => x.LastName
        (f1, f2) => 
        f1 != this.Model.FirstName
        || f2 != this.Model.LastName
        );
    }

    protected override void SaveModel() {
        Model.FirstName = this.FirstName;
        Model.LastName = this.LastName;
        Save(Model); 
        // want to force IsDirty to re-evaluate here and return false.
    }

谢谢 :-)

我认为这应该很容易。今天早上我一定是 'pre coffee'。

protected Subject<Unit> Saved = new Subject<Unit>();

protected override IObservable<bool> IsDirty() {
        return this.WhenAnyValue 
        (x => x.Firstname,
         x => x.LastName
        (f1, f2) => 
        f1 != this.Model.FirstName
        || f2 != this.Model.LastName
        ).Merge(Saved.Select(x => false));
}

protected override void SaveModel() {
    Model.FirstName = this.FirstName;
    Model.LastName = this.LastName;
    Save(Model); 
    this.Saved.OnNext(new Unit());
}

虽然您的主题解决方案可行,但我相信您可以做得更好。我假设您提供的代码取自视图模型。鉴于该假设:

1) SaveModel should be a Command

2) IsDirty should be an output property

如果您应用此更改,您最终会得到一个没有额外 Subject(耶!)

的代码
// in class
public ReactiveCommand<Unit> SaveCommand { get; }

private readonly ObservableAsPropertyHelper<bool> _isDirty;
public bool IsDirty { get { return _isDirty.Value; } }


// in constructor
this.SaveCommand = ReactiveCommand.CreateAsyncTask(_ => 
{
    Model.FirstName = this.FirstName;
    Model.LastName = this.LastName;
    Save(Model); // this could be an async method
    return Task.FromResult(Unit.Default);
});

this.WhenAnyValue(
    vm => vm.Firstname,
    vm => vm.LastName,
    (f1, f2) => Unit.Default)
    .Select(_ => this.FirstName != this.Model.FirstName 
              || this.LastName != this.Model.LastName)
    .Merge(this.SaveCommand.select(x => false))
    .ToProperty(this, vm => vm.IsDirty, out _isDirty);

这利用了 ReactiveCommand 本身实现的事实 IObservable 持有与您的主题相同的信息。