嘗試使用RX模擬系統發送來自多個發佈者的通知。合併RX中的多個自定義觀測值
我有兩個自定義接口ITopicObservable和ITopicObserver來模擬實現類除了IObservable和IObserver接口之外還有其他屬性和方法的事實。
我現在的問題是我的想法是我應該可以添加一些observables在一起,將它們合併在一起並訂閱觀察者以提供來自所有合併的observables的更新。但是,帶有「問題」註釋的代碼會拋出無效的轉換異常。
用例是一些獨立的傳感器,每個傳感器都會監測一個盒子中的溫度,例如將所有報告彙總到溫度健康狀況監測器隨後訂閱的一個溫度報告。
我在這裏錯過了什麼?還是有更好的方法來實現使用RX的情況?下面
using System;
using System.Reactive.Linq;
using System.Collections.Generic;
namespace test
{
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ("Hello World!");
var to = new TopicObserver();
var s = new TopicObservable ("test");
var agg = new AggregatedTopicObservable();
agg.Add (s);
agg.Subscribe (to);
}
}
public interface ITopicObservable<TType>:IObservable<TType>
{
string Name{get;}
}
public class TopicObservable:ITopicObservable<int>
{
public TopicObservable(string name)
{
Name = name;
}
#region IObservable implementation
public IDisposable Subscribe (IObserver<int> observer)
{
return null;
}
#endregion
#region ITopicObservable implementation
public string Name { get;private set;}
#endregion
}
public class AggregatedTopicObservable:ITopicObservable<int>
{
List<TopicObservable> _topics;
private ITopicObservable<int> _observable;
private IDisposable _disposable;
public AggregatedTopicObservable()
{
_topics = new List<TopicObservable>();
}
public void Add(ITopicObservable<int> observable)
{
_topics.Add ((TopicObservable)observable);
}
#region IObservable implementation
public IDisposable Subscribe (IObserver<int> observer)
{
_observable = (ITopicObservable<int>)_topics.Merge();
_disposable = _observable.Subscribe(observer);
return _disposable;
}
#endregion
#region ITopicObservable implementation
public string Name { get;private set;}
#endregion
}
public interface ITopicObserver<TType>:IObserver<TType>
{
string Name{get;}
}
public class TopicObserver:ITopicObserver<int>
{
#region IObserver implementation
public void OnNext (int value)
{
Console.WriteLine ("next {0}", value);
}
public void OnError (Exception error)
{
Console.WriteLine ("error {0}", error.Message);
}
public void OnCompleted()
{
Console.WriteLine ("finished");
}
#endregion
#region ITopicObserver implementation
public string Name { get;private set;}
#endregion
}
}
非常感謝!爲了回答關於接口使用的問題,我們例如有許多溫度探頭監測系統的不同部分。每個探針都有一個唯一的ID /名稱他們獨立記錄他們的溫度文件。將會有一個聚合溫度監控器有效地監控整個系統,這是AggregatedTopic進入的地方。還會有另一個實體(Observer)根據AggregatedTopic信息做出打開或關閉的決定。所有這些與日誌記錄。有沒有更好的方法來實現這一目標? – Bernard
@Bernard - 是的,有一個更簡單的方法來做到這一點。您不應該擴展接口。相反,您應該創建一個包含所生成的id,名稱和值的自定義對象。然後你創建可觀察對象來返回這個自定義對象 - 你可以很簡單地進行合併。你真的應該問這是一個單獨的問題,我很樂意給你一個答案。如果你願意的話,請詳細告訴你如何知道溫度探頭什麼時候產生一個值(顯示代碼)。 – Enigmativity
我已根據要求創建了一個新問題http://stackoverflow.com/questions/36723106/building-a-sensor-monitoring-system-using-rx。非常感謝您的幫助! – Bernard