强制WhenAnyValue重新评估

时间:2015-12-13 20:49:40

标签: c# reactiveui

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

'E'

谢谢: - )

2 个答案:

答案 0 :(得分:3)

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

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保存与主题相同的信息这一事实。

答案 1 :(得分:0)

我认为应该很容易。我一定是过咖啡&#39;今天早上。

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());
}