响应式扩展:包装自定义委托事件

Reactive extensions: Wrap custom delegate event

如何使用 Observable.FromEvent 将这些自定义委托包装在 Rx 中?

public delegate void EmptyDelegate();
public delegate void CustomDelegate( Stream stream, Dictionary<int, object> values );

空委托

这是一个无参数委托,但流需要一个类型——Rx 为此目的定义了 Unit,以指示我们只对事件的发生感兴趣的事件类型——也就是说,没有有意义的负载.

假设您有一个此委托的实例声明为:

public EmptyDelegate emptyDelegate;

那么你可以这样做:

var xs = Observable.FromEvent<EmptyDelegate, Unit>(
    h => () => h(Unit.Default),
    h => emptyDelegate += h,
    h => emptyDelegate -= h);

xs.Subscribe(_ => Console.WriteLine("Invoked"));

emptyDelegate(); // Invoke it

自定义委托

假设您同时需要流和值,您将需要一个类型来承载它们,例如:

public class CustomEvent
{
    public Stream Stream { get; set; }
    public Dictionary<int,object> Values { get; set; }
}

然后假设声明了一个委托实例:

public CustomDelegate customDelegate;

你可以做到:

var xs = Observable.FromEvent<CustomDelegate, CustomEvent>(
    h => (s, v) => h(new CustomEvent { Stream = s, Values = v }),
    h => customDelegate += h,
    h => customDelegate -= h);

xs.Subscribe(_ => Console.WriteLine("Invoked"));

// some data to invoke the delegate with
Stream stream = null;
Dictionary<int,object> values = null;

// and invoke it
customDelegate(stream,values);

有关 Observable.FromEvent 的详细说明,请参阅 How to use Observable.FromEvent instead of FromEventPattern and avoid string literal event names