反应式扩展配置事件处理程序

时间:2013-05-04 20:05:22

标签: c# system.reactive

大家好我有一个不断触发实时数据的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

2 个答案:

答案 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;
        });
    });
}    

编辑:愚蠢的拼写错误