c# - How to convert an event to an IObservable when it doesn't conform to the standard .NET event pattern -


i have delegate looks this:

public delegate void mydelegate(int arg1, int arg2); 

and event looks this:

public event mydelegate somethinghappened; 

is there easy way create iobservable sequence event? i'd (but doesn't compile):

var obs = observable.fromeventpattern<int, int>(this, "somethinghappened"); var subscription = obs.subscribe(x,y => dosomething(x, y)); 

....

private void dosomething(int value1, int value2) { ... } 

there way using observable.fromevent follows.

lets create class test encapsulate delegate , event definition:

public class test {        public delegate void mydelegate(int arg1, int arg2);      public event mydelegate somethinghappened;      public void raiseevent(int a, int b)     {         var temp = somethinghappened;         if(temp != null)         {             temp(a, b);         }     }     } 

now, because delegate has 2 arguments not neatly packaged subclass of eventargs, must use conversion function package them suitable containing type. if recall signature of onnext method of iobservable should clear why have - can supply single argument here.

you can create own type this, lazy , use tuple<int,int>. can use overload of observable.fromevent conversion function follows:

var test = new test();  var obs = observable.fromevent<test.mydelegate, tuple<int,int>>(     handler => (a, b) => handler(tuple.create(a,b)),     h => test.somethinghappened += h,     h => test.somethinghappened -= h ); 

to clear, supplying in first parameter function accepts onnext handler (in case of type action<tuple<int,int>>) , returns delegate can subscribed event (of type mydelegate). delegate invoked each event , in turn invoke onnext handler passed in subscribe call. end stream of type iobservable<tuple<int,int>>.

with obs in place, can subscribe so:

var subscription = obs.subscribe(x => console.writeline(x.item1 + " " + x.item2)); 

and test this:

test.raiseevent(1, 2); 

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -