简体   繁体   English

从非标准事件创建 Observable(无 EventArgs / EventHandler)

[英]Create Observable from non-standard event (no EventArgs / EventHandler)

I would like to create an Observable for an event defined as follows:我想为如下定义的事件创建一个 Observable:

public event Func<Exception, Task> Closed;

The current code I have is this:我目前的代码是这样的:

Observable.FromEvent<Func<Exception, Task>, Unit>(h => hub.Closed += h, h=> hub.Closed -= h); 

It compiles OK, but it throws this 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.' System.ArgumentException: '无法绑定到目标方法,因为其签名或安全透明度与委托类型不兼容。'

I feel that I'm doing it wrong.我觉得我做错了。 I'm not used to create observables from events that don't follow the EventArgs pattern 😔我不习惯从不遵循 EventArgs 模式的事件中创建 observable 😔

EDIT: Just for clarification purposes, this is the complete code with how the classic event handling would look:编辑:为了澄清起见,这是经典事件处理的完整代码:

class Program
{
    static async Task Main(string[] args)
    {
        var hub = new HubConnectionBuilder().WithUrl("http://localhost:49791/hubs/status")
            .Build();

        hub.On<Status>("SendAction", status => Console.WriteLine($"Altitude: {status.Altitude:F} m"));
        await hub.StartAsync();

        hub.Closed += HubOnClosed;

        while (true)
        {
        }
    }

    private static Task HubOnClosed(Exception arg)
    {
        Console.WriteLine("The connection to the hub has been closed");
        return Task.CompletedTask;
    }
}

You need the conversion overload.您需要转换重载。 I shutter every time I look this thing up:每次看这个东西我都会关门:

IObservable<TEventArgs> Observable.FromEvent<TDelegate, TEventArgs>(
    Func<Action<TEventArgs>, TDelegate> conversion, 
    Action<TDelegate> addHandler, 
    Action<TDelegate> removeHandler>
)

So in our case, TEventArgs is Exception , and TDelegate is Func<Exception, Task> , so you need to convert Action<Exception> to Func<Exception, Task>> , in other words: Func<Action<Exception>, Func<Exception, Task>> .所以在我们的例子中, TEventArgsException ,而TDelegateFunc<Exception, Task> ,所以你需要将Action<Exception>转换为Func<Exception, Task>> ,换句话说: Func<Action<Exception>, Func<Exception, Task>> I'm assuming that conversion looks like this: a => e => {a(e); return Task.CompletedTask; }我假设转换看起来像这样: a => e => {a(e); return Task.CompletedTask; } a => e => {a(e); return Task.CompletedTask; } a => e => {a(e); return Task.CompletedTask; } . a => e => {a(e); return Task.CompletedTask; } .

System.Reactive needs this conversion function because it needs to subscribe to the event with a proper delegate, and somehow hook in your code/RX Plumbing code. System.Reactive 需要这个转换函数,因为它需要使用适当的委托订阅事件,并以某种方式挂钩您的代码/RX Plumbing 代码。 In this case, a(e) is basically RX plumbing which then passes on the Exception to be handled later in the reactive pipeline.在这种情况下, a(e)基本上是 RX 管道,然后将异常传递到稍后在反应管道中处理。

Full code:完整代码:

class Program
{
    static async Task Main(string[] args)
    {

        Program.Closed += Program.HubOnClosed;
        Observable.FromEvent<Func<Exception, Task>, Exception>(
            a => e => {a(e); return Task.CompletedTask; }, 
            h => Program.Closed += h, 
            h => Program.Closed -= h
        )
            .Subscribe(e =>
            {
                Console.WriteLine("Rx: The connection to the hub has been closed");
            });

        Program.Closed.Invoke(null);
        Program.Closed.Invoke(null);
    }

    private static Task HubOnClosed(Exception arg)
    {
        Console.WriteLine("The connection to the hub has been closed");
        return Task.CompletedTask;
    }

    public static event Func<Exception, Task> Closed;
}

Does something like this do the trick?这样的事情有用吗?

class Program
{
    public event Func<Exception, Task> Closed;

    static void Main(string[] args)
    {
        Program p = new Program();
        IObservable<Unit> closedObservable = Observable.Create<Unit>(
            observer =>
            {
                Func<Exception, Task> handler = ex =>
                {
                    observer.OnNext(Unit.Default);
                    return Task.CompletedTask;
                };

                p.Closed += handler;

                return () => p.Closed -= handler;
            });
    }
}

Observable.Create() is a useful fallback for unusual cases like this. Observable.Create()是处理此类异常情况的有用回退方法。

As an aside, it's very strange to have an event with a non-void returning delegate, since the code that raises the event would only see the value of the last handler to run - unless it raises the event in some non-standard way.顺便说一句,具有非空返回委托的事件非常奇怪,因为引发事件的代码只会看到要运行的最后一个处理程序的值 - 除非它以某种非标准方式引发事件。 But, since it's library code, that's out of your hands!但是,由于它是库代码,这超出了您的掌握!

Try the following, not using the signature you want but something to try:尝试以下操作,不要使用您想要的签名,而是尝试一些东西:

class Program
{
        public delegate void ClosedEventHandler(object sender, Func<Exception, Task> e);
        public ClosedEventHandler Closed { get; set; }    

        static void Main(string[] args)
        {
            Program hub = new Program();
            hub.Closed = hub.SomethingToDoWhenClosed;    
            Observable
                .FromEventPattern<ClosedEventHandler, Func<Exception, Task>>(
                    h => hub.Closed += h,
                    h => hub.Closed -= h)
                .Subscribe(x =>
                {
                    // this is hit
                });    
            hub.Closed(hub, e => null);
        }

        public void SomethingToDoWhenClosed(object sender, Func<Exception, Task> e)
        {
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM