【问题标题】:How can I subscribe and cast SourceList.Count to IObservable?如何订阅并将 SourceList.Count 转换为 IObservable?
【发布时间】:2020-08-17 14:31:52
【问题描述】:

我创建了 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();
}

更新:

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

【问题讨论】:

    标签: c# system.reactive dynamic-data reactiveui


    【解决方案1】:

    你可以这样做:

    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 以获取代码参考。

    【讨论】:

    • .Count() 仅在底层可观察对象结束时返回一个值。你会得到一个值,让你知道序列在完成之前产生了多少值。
    • 我怀疑它会更像.Connect().Select(x =&gt; x.Count()).Where(x =&gt; x == 0),但我无法确定这一点。可以测试吗?
    • ISourceCache 恰好公开了一个名为 CountChanged 的​​ IObservable&lt;bool&gt; 属性。以下是一些显示用法的单元测试:github.com/reactiveui/DynamicData/blob/…
    • @enigmativity 使用动态数据聚合运算符而不是 Rx 扩展。 github.com/reactiveui/dynamicdata#aggregation 这个解决方案应该可以在上面运行。
    • @GlennWatson - 很公平,但是天啊,拥有多个同名但语义不同的扩展方法会让人感到困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多