如何订阅SourceList.Count并将其强制转换为IObservable?

问题描述

我创建ValidatableModelBase类,但遇到了一些麻烦。我需要订阅SourceCache的更改,并将Count集合转换为IObservable bool。我该怎么办?

private readonly SourceCache<ValidationResult,string> _results;

public IObservalbe<bool> IsValid { get; }

public ValidatableModelBase()
{
    _results = new SourceCach<ValidationResult,string>(x => x.PropertyName);

    //Doesn't work. I think because i dont .Subscribe() to changes?
    IsValid = _results.Connect().IsEmpty();
}

upd:

HasErrors = collection.CountChanged.Subscribe(x => {Count = x;});
IsValid = this.WhenAnyValie(x => x.HasErrors).Select(x => x == 0);

解决方法

您可以执行以下操作:

var databasesValid = collectionOfReactiveObjects
    .Connect().Count().Select(x => x == 0);

// Then you can convert that IObservable<bool> to a view model
// property declared as ObservableAsPropertyHelper<bool>.
_databasesValid = databasesValid.ToProperty(this,x => x.DatabasesValid);

您需要包括DynamicData.Aggregation名称空间。

有关代码参考,请参见https://github.com/reactiveui/DynamicData/blob/63960b0fa7bd0362c40e137498cd0014ba02f3dc/src/DynamicData/Aggregation/CountEx.cs#L57