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

Sup*_*JMN 3 .net c# events system.reactive observable

我想为如下定义的事件创建一个 Observable:

public event Func<Exception, Task> Closed;
Run Code Online (Sandbox Code Playgroud)

我目前的代码是这样的:

Observable.FromEvent<Func<Exception, Task>, Unit>(h => hub.Closed += h, h=> hub.Closed -= h); 
Run Code Online (Sandbox Code Playgroud)

它编译正常,但它抛出这个运行时异常:

System.ArgumentException: '无法绑定到目标方法,因为其签名或安全透明度与委托类型不兼容。'

我觉得我做错了。我不习惯从不遵循 EventArgs 模式的事件中创建 observable

编辑:为了澄清起见,这是经典事件处理的完整代码:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Shl*_*omo 7

您需要转换重载。每次看这个东西我都会关门:

IObservable<TEventArgs> Observable.FromEvent<TDelegate, TEventArgs>(
    Func<Action<TEventArgs>, TDelegate> conversion, 
    Action<TDelegate> addHandler, 
    Action<TDelegate> removeHandler>
)
Run Code Online (Sandbox Code Playgroud)

所以在我们的例子中,TEventArgsisException和TDelegateis Func<Exception, Task>,所以你需要转换Action<Exception>为Func<Exception, Task>>,换句话说:Func<Action<Exception>, Func<Exception, Task>>。我假设转换看起来像这样:a => e => {a(e); return Task.CompletedTask; }。

System.Reactive 需要这个转换函数,因为它需要使用适当的委托订阅事件,并以某种方式挂钩您的代码/RX Plumbing 代码。在这种情况下,a(e)基本上是 RX 管道,然后将异常传递给稍后在反应管道中处理。

完整代码:

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;
}
Run Code Online (Sandbox Code Playgroud)