7

我有一个类似 ReactiveUI 的视图模型。它有几个触发NotifyPropertyChanged事件的不同类型的属性,我想订阅一个在触发任何事件时将调用的方法,但我对实际值不感兴趣。

我当前的代码有点难看(由于不透明的true选择)。有没有办法表达这一点,表明事件发生时只是关心的意图?

    this.ObservableForProperty(m => m.PropertyOne)
        .Select(_ => true)
        .Merge(this.ObservableForProperty(m => m.PropertyTwo).Select(_ => true))
   .Subscribe(...)

我正在合并大约 8 个属性,所以它比显示的更难看。

4

2 回答 2

17

既然这看起来像 ReactiveUI,那么使用 WhenAny 运算符怎么样:

this.WhenAny(x => x.PropertyOne, x => x.PropertyTwo, (p1, p2) => Unit.Default)
    .Subscribe(x => /* ... */);

不过,一般来说,如果你正在组合任意 Observable,你也可以使用非扩展方法更清楚地写出来:

Observable.Merge(
    this.ObservableForProperty(x => x.PropertyOne).Select(_ => Unit.Default),
    this.ObservableForProperty(x => x.PropertyTwo).Select(_ => Unit.Default),
    this.ObservableForProperty(x => x.PropertyThree).Select(_ => Unit.Default)
).Subscribe(x => /* ... */);

此外,如果您要订阅 ReactiveObject 的每个属性,最好只使用:

this.Changed.Subscribe(x => /* ... */);
于 2011-11-05T16:03:19.477 回答
2

您可以将其作为扩展方法以使意图更清晰:

public static IObservable<bool> IgnoreValue<T>(this IObservable<T> source)
{
    return source.Select(_ => true);
}

...

this.ObservableForProperty(m => m.PropertyOne).IgnoreValue()
.Merge(this.ObservableForProperty(m => m.PropertyTwo).IgnoreValue())
.Subscribe(..);
于 2011-11-05T02:31:37.917 回答