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

Lap*_*ish 1 c# dynamic-data system.reactive reactiveui

我创建 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();
}
Run Code Online (Sandbox Code Playgroud)

更新:

HasErrors = collection.CountChanged.Subscribe(x => {Count = x;});
IsValid = this.WhenAnyValie(x => x.HasErrors).Select(x => x == 0);
Run Code Online (Sandbox Code Playgroud)

Gle*_*son 5

你可以这样做:

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);
Run Code Online (Sandbox Code Playgroud)

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

请参阅https://github.com/reactiveui/DynamicData/blob/63960b0fa7bd0362c40e137498cd0014ba02f3dc/src/DynamicData/Aggregation/CountEx.cs#L57此处获取代码参考。

  • @enigmativity 使用动态数据聚合运算符而不是 Rx 扩展。https://github.com/reactiveui/dynamicdata#aggregation 这个解决方案应该可以在上面工作。 (2认同)