响应式扩展:包装自定义委托事件
作者:互联网
如何使用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
CustomDelegate
假设您同时需要流和值,则需要一种类型来携带这些内容,例如:
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.
标签:system-reactive,c 来源: https://codeday.me/bug/20191120/2045463.html