[英]Reactive extensions: Wrap custom delegate event
How do I use Observable.FromEvent to wrap these custom delegates in Rx? 如何使用Observable.FromEvent在Rx中包装这些自定义委托?
public delegate void EmptyDelegate();
public delegate void CustomDelegate( Stream stream, Dictionary<int, object> values );
This is a parameterless delegate, but streams need a type - Rx defines Unit
for this purpose, to indicate an event type that we are only interested in occurrences of - that is, there is no meaningful payload. 这是一个无参数的委托,但是流需要一个类型 - 为此目的,Rx定义了
Unit
,以指示我们只对出现感兴趣的事件类型 - 也就是说,没有有意义的有效负载。
Assuming you have an instance of this delegate declare as: 假设您有此委托的实例声明为:
public EmptyDelegate emptyDelegate;
Then you can do: 然后你可以这样做:
var xs = Observable.FromEvent<EmptyDelegate, Unit>(
h => () => h(Unit.Default),
h => emptyDelegate += h,
h => emptyDelegate -= h);
xs.Subscribe(_ => Console.WriteLine("Invoked"));
emptyDelegate(); // Invoke it
Assuming you need both the stream and values, you will need a type to carry these such as: 假设您需要流和值,您将需要一个类型来携带这些,如:
public class CustomEvent
{
public Stream Stream { get; set; }
public Dictionary<int,object> Values { get; set; }
}
Then assuming an instance of the delegate is declared: 然后假设委托的实例被声明:
public CustomDelegate customDelegate;
You can do: 你可以做:
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);
For a detailed explanation of Observable.FromEvent
see How to use Observable.FromEvent instead of FromEventPattern and avoid string literal event names . 有关
Observable.FromEvent
的详细说明,请参阅如何使用Observable.FromEvent而不是FromEventPattern并避免使用字符串文字事件名称 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.