[英]Wrap Observable.FromEventPattern with Observable.Create
Which is the difference between this (taken from RxCookbook on GitHub ):这之间的区别(取自GitHub 上的 RxCookbook ):
public static IObservable<TProperty> OnPropertyChanges<T, TProperty>(this T source, Expression<Func<T, TProperty>> property)
where T : INotifyPropertyChanged
{
return Observable.Create<TProperty>(o=>
{
var propertyName = property.GetPropertyInfo().Name;
var propertySelector = property.Compile();
return Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
handler => handler.Invoke,
h => source.PropertyChanged += h,
h => source.PropertyChanged -= h)
.Where(e => e.EventArgs.PropertyName == propertyName)
.Select(e => propertySelector(source))
.Subscribe(o);
});
}
And this (written by myself):还有这个(我自己写的):
public static IObservable<TProperty> OnPropertyChanges<T, TProperty>(this T source, Expression<Func<T, TProperty>> property)
where T : INotifyPropertyChanged
{
var propertyName = property.GetPropertyInfo().Name;
var propertySelector = property.Compile();
return Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
handler => handler.Invoke,
h => source.PropertyChanged += h,
h => source.PropertyChanged -= h)
.Where(e => e.EventArgs.PropertyName == propertyName)
.Select(e => propertySelector(source));
}
I think that in the second block of code, propertyName
and propertySelector
will be evaluated when OnPropertyChanges
is called and in the first block these variables will be evaluated every time someone subscribes to the observable.我认为在第二个代码块中,当
OnPropertyChanges
被调用时, propertyName
和propertySelector
将被评估,并且在第一个块中,每当有人订阅可观察对象时,这些变量将被评估。 However, I can't figure out if/why the first block is preferrable to the second one, and why did the author of the first block decided to use Observable.Create
.但是,我无法弄清楚第一个块是否/为什么比第二个更可取,以及为什么第一个块的作者决定使用
Observable.Create
。
Answer from the author of the first block of code on GitHub :来自GitHub上第一块代码的作者的回答:
My stance on this is that calling a method that returns an IObservable should do nothing.
我对此的立场是调用返回 IObservable 的方法不应该做任何事情。 It is the subscription to that returned value that should invoke any side effects or processing.
应该调用任何副作用或处理的是对该返回值的订阅。
If a subscription cost needs to be amortised across numerous subscriptions then the various multicast options in Rx should be applied.
如果订阅成本需要在多个订阅之间分摊,则应应用 Rx 中的各种多播选项。
In this specific case, the argument is weak, however it then muddies the pattern and opens the door for other methods to "do work" without a subscription.
在这种特定情况下,这个论点很弱,但是它会混淆模式并为其他方法打开大门,无需订阅即可“工作”。 I see this as a very common mistake and a source of race conditions and leaking resources (think opening a connection, starting a timer etc)
我认为这是一个非常常见的错误,也是竞争条件和资源泄漏的根源(想想打开连接、启动计时器等)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.