4

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 );
James World
  • 29,019
  • 9
  • 86
  • 120
Mauro Sampietro
  • 2,739
  • 1
  • 24
  • 50

1 Answers1

4

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.

Community
  • 1
  • 1
James World
  • 29,019
  • 9
  • 86
  • 120