如何使用 IObservable 订阅 TypedEventHandler<T, TArgs> 事件

How to subscribe to TypedEventHandler<T, TArgs> event using IObservable

我正在尝试以下操作,

var _connectedAnimation = ConnectedAnimationService.GetForCurrentView().GetAnimation("forwardAnimation");

Observable.FromEvent<TypedEventHandler<ConnectedAnimation, object>, object>(
          handler => _connectedAnimation.Completed += handler,
          handler => _connectedAnimation.Completed -= handler)

但是,当引发事件时,我得到了运行时异常

System.ArgumentException: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.
  at System.Delegate.CreateDelegate(Type type, Object firstArgument, MethodInfo method, Boolean throwOnBindFailure)
  at System.Reactive.ReflectionUtils.CreateDelegate[TDelegate](Object o, MethodInfo method) in D:\a\s\Rx.NET\Source\src\System.Reactive\Internal\ReflectionUtils.cs:line 24
  at System.Reactive.Linq.ObservableImpl.FromEvent`2.GetHand

完成的事件定义为

public sealed class ConnectedAnimation : IConnectedAnimation, IConnectedAnimation2, IConnectedAnimation3
{
    /// <summary>Occurs when the animation is finished.</summary>
    public extern event TypedEventHandler<ConnectedAnimation, object> IConnectedAnimation.Completed;
}

由于不是标准事件,也因为有多个事件参数,我们需要创建一个Tuple。参考Rx.Net in Action中的4.2.3. Events with multiple parameters

Observable.FromEvent<TypedEventHandler<ConnectedAnimation, object>, Tuple<ConnectedAnimation, object>>(
    rxHandler => (animation, o)=> rxHandler(Tuple.Create(animation,o)),
    handler => _connectedAnimation.Completed += handler,
    handler => _connectedAnimation.Completed -= handler)