我试图从一个动作创建一个Observable,但是FromEventPattern
和FromEvent
的语法对我来说很难。
这是我的尝试:
Observable
.FromEventPattern<Action<IStreamTrade>, IStreamTrade>(
x => _polygonSocket.TradeReceived += x,
x => _polygonSocket.TradeReceived -= x)
.Select(x => x?.EventArgs)
.IsNotNull()
.Subscribe( /** do stuff **/)
.DisposeWith(Bindings);
我觉得FromEventPattern
在这里可能不是正确的选择,但是我无法编译其他任何东西。
会发生什么:
我收到一个Parameter count mismatch.
异常,看起来像这样:
Parameter count mismatch.
Thread started: #26
at System.Delegate.CreateDelegate (System.Type type, System.Object firstArgument, System.Reflection.MethodInfo method, System.Boolean throwOnBindFailure, System.Boolean allowClosed) [0x000ee] in /Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/external/mono/mcs/class/corlib/System/Delegate.cs:230
at System.Delegate.CreateDelegate (System.Type type, System.Object firstArgument, System.Reflection.MethodInfo method) [0x00000] in /Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/external/mono/mcs/class/corlib/System/Delegate.cs:296
at System.Reactive.ReflectionUtils.CreateDelegate[TDelegate] (System.Object o, System.Reflection.MethodInfo method) [0x00000] in <370f6a6bb34048878534065376a195cb>:0
at System.Reactive.Linq.ObservableImpl.FromEventPattern+Impl`2[TDelegate,TEventArgs].GetHandler (System.Action`1[T] onNext) [0x0003d] in <370f6a6bb34048878534065376a195cb>:0
at System.Reactive.Linq.ObservableImpl.EventProducer`2+Session[TDelegate,TArgs].Initialize () [0x00023] in <370f6a6bb34048878534065376a195cb>:0
at System.Reactive.Linq.ObservableImpl.EventProducer`2+Session[TDelegate,TArgs].Connect (System.IObserver`1[T] observer) [0x00033] in <370f6a6bb34048878534065376a195cb>:0
我在寻找什么
我想学习如何从Action<IStreamTrade>
创建Observable。我愿意使用Observable.Create
解决方案,但如果可能的话,我更喜欢使用FromEvent
或FromEventPattern
的解决方案。
一些其他信息:
操作定义如下:
public event Action<IStreamTrade> TradeReceived;
这是他们在示例代码中的使用方式:
sockClient.OnTradeUpdate += HandleTradeUpdate;
// later ...
private void HandleTradeUpdate(ITradeUpdate trade)
{
// removed irrelevant code
}
答案 0 :(得分:2)
尝试使用Observable.FromEvent
,它将基于Action的通用.NET事件转换为可观察的序列:
Observable.FromEvent<IStreamTrade>(
x => _polygonSocket.TradeReceived += x,
x => _polygonSocket.TradeReceived -= x)
.Subscribe( /** do stuff **/)
.DisposeWith(Bindings);
答案 1 :(得分:0)
虽然我更喜欢,但使用了Vitali的方法。这是使用Observable.Create
的另一种方法。
Observable
.Create<IStreamTrade>(
x =>
{
Action<IStreamTrade> aist = st => x.OnNext(st);
_polygonSocket.TradeReceived += aist;
return Disposable.Create(() => _polygonSocket.TradeReceived -= aist);
})
.Subscribe()
.DisposeWith(Bindings);