这可能太含糊了。我需要一个既是IObserver<T>又是IOservable<T>的类的简单示例。T实际上是相同的类型。
OnNext将自己创建一个IOBservable<T>序列。尽管如此,应该防止this观察自己。本质上,观察者部分订阅了多个可观察对象,并聚合了它们的值,然后反过来将该聚合服务于其他订阅者。
它是像继承/实现IObserver<T>和IOservable<T>一样简单,还是我在这里以错误的方式思考可组合性?
public struct T
{
}
public class ObserverAndObservable : IObserver<T>, IObservable<T>
{
}我想要实现的是这样的东西。想象一下,我有一张定位卫星的清单,每一颗卫星都属于世界上不同的国家。我想订阅说,美国人(或任何有用的组合),然后计算他们的平均GPS位置。
//Satellites are constantly emiting realtime data
List<Satellite> satellites;
IOBserver<Satellite> observer = satellites.ToObservable();
IDisposable observable = observer.Where(x => string.Equals(x.Name, "USSatellite")).Subscribe();
//Now, compute the GPS average of the Satellites.
//This is not very fluent. There is probably a way to compose these
//functions using a lambda at the end to do the computation, which in turn
//can be subscribed to by other IOBservers...发布于 2015-08-12 13:01:58
您所描述的模式称为装饰者模式。它不仅是有效的,而且绝大多数Rx.Linq都是用这种模式实现的。
至于你是否应该这样做的问题,我会说不。在Rx.Linq中已经有了大量的装饰器。
Rx的要点是您可以在函数式编程中处理事件。因此,您应该学习使用Rx.Net附带的monads,而不是尝试使用过程化编程paradime来构建您的行为。
编辑:这是一个你可以实现普通monad的例子。
public static class Foo
{
public static IObservable<double> GetAverageOfLatest(this IEnumerable<IObservable<double>> sources)
{
int count = 1;
var sums = sources.Aggregate(
(left, right) =>
{
//count how many satellites you have.
count ++;
return Observable.CombineLatest(left, right, (l, r) => l + r);
});
return sums.Select(sum => sum / count);
}
}发布于 2015-08-12 12:46:21
从技术上讲,让一个类同时实现IObservable<T>和IObserver<T>并没有错,但由于每个接口都隐含着一个责任,因此这样做可能会违反single responsibility principle。
我能想象到的唯一远程有用的情况是一种“观察者代理”,但这听起来并不是很有用。
https://stackoverflow.com/questions/31955791
复制相似问题