resp78
resp78

Reputation: 1534

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

I was trying the following,

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

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

However, when the event is raised I get the runtime exception

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\1\s\Rx.NET\Source\src\System.Reactive\Internal\ReflectionUtils.cs:line 24
  at System.Reactive.Linq.ObservableImpl.FromEvent`2.GetHand

The completed event is defined as

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

Upvotes: 0

Views: 199

Answers (1)

resp78
resp78

Reputation: 1534

Since it is not a standard event and also because there are multiple event arguments, we need to create a Tuple. Refer to 4.2.3. Events with multiple parameters in Rx.Net in Action.

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

Upvotes: 2

Related Questions