简体   繁体   中英

Reactive extensions: Wrap custom delegate event

How do I use Observable.FromEvent to wrap these custom delegates in Rx?

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

EmptyDelegate

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.

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

CustomDelegate

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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