当返回类型不重要时,是否有更优雅的方法来合并可观察对象

本文关键字:方法 合并 对象 观察 不重要 返回类型 是否 | 更新日期: 2023-09-27 18:13:36

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

我当前的代码有点难看(由于不透明的true选择)。是否有一种方式可以表达出当事件发生时你只是关心的意图?

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

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

当返回类型不重要时,是否有更优雅的方法来合并可观察对象

由于这看起来像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 => /* ... */);

你可以把它变成一个扩展方法,使意图更清晰:

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