大家好我有一个不断触发实时数据的ExternalDataService,它包含在lib中。
我有一个包装类,它订阅并将更新放在Observable上。
public class MyService
{
private ExternalDataService _externalDataService;
public MyService()
{
_externalDataService= new ExternalDataService ();
}
public IObservable<double> GetData()
{
return Observable.Create<double>(i =>
{
_externalPriceService.OnDataChanged += (s, e) => { i.OnNext(e); };
return () =>
{
// what do I do here?
};
});
}
}
消费为......
var p = new MyService();
var disposable = p.GetData().Subscribe(i => Console.WriteLine(i));
当_externalPriceService.OnDataChanged
被一次性调用时,我如何取消订阅Dispose
?
答案 0 :(得分:3)
使用Observable.FromEvent或Observable.FromEventPattern,而不是Observable.Create。然后你只需处理订阅。
根据您的EventHandler定义,它将是这样的:
public class ExternalDataService {
public EventHandler<DataChangedEventArgs> OnDataChanged;
}
public class DataChangedEventArgs : EventArgs {
public Double Data {
get; set;
}
}
public class MyService {
private ExternalDataService _externalDataService;
public MyService()
{
_externalDataService= new ExternalDataService ();
}
public IObservable<double> GetData()
{
return Observable.FromEventPattern<DataChangedEventArgs>(eh => _externalDataService.OnDataChanged += eh, eh => _externalDataService.OnDataChanged -= eh)
.Select(e => e.EventArgs.Data);
}
}
答案 1 :(得分:2)
您也可以这样做:
public IObservable<double> GetData()
{
Action<object, double> dataHandler = null;
return Observable.Create<double>(i =>
{
dataHandler = (s, e) => { i.OnNext(e); };;
_externalDataService.OnDataChanged += dataHandler;
return Disposable.Create(() =>
{
_externalDataService.OnDataChanged -= dataHandler;
});
});
}
编辑:愚蠢的拼写错误