简体   繁体   中英

How to create IObservable from delegate?

This code:

// NOTE: IQuote DOES NOT inherit from EventArgs
public interface IQuote// : EventArgs
{
}

class C
{
   //NOTE, this is NOT public event EventHandler<IQuote> QuoteChangeEvent;
    public delegate void QuoteChangeEvent(IQuote q);
}

var c = new C();

c.OnQuoteChange += ProcessQuoteChange;


public static void ProcessQuoteChange(IQuote q)
{
}

works fine. Now I want to use Rx . This doesn't work, ie, it doesn't even compile:

var priceChangedObservable = Observable.FromEvent<QuoteChangeEvent, QuoteChangeEvent>(
    (handler) =>
    {
        QuoteChangeEvent quoteHandler = (e) => handler(e);                   
    },
    eh => c.OnQuoteChange += eh,
    eh => c.OnQuoteChange -= eh
    );

On the line (handler) =>

- "Severity Code    Description Project File    Line    Suppression State   
   Error    CS1643  Not all code paths return a value in lambda expression  
   of type 'Func<Action<QuoteChangeEvent>,   
   QuoteChangeEvent>'       294 Active"

On the handler(e)

Error CS1503 Argument 1: cannot convert from 'IQuote' to 'QuoteChangeEvent' 296 Active

What is the correct way to create an IObservable from a delegate ?

When using Observable.FromEvent<TDelegate, TEventArgs> , you should pass <QuoteChangeEvent, IQuote> :

var priceChangedObservable = Observable.FromEvent<QuoteChangeEvent, IQuote>(
    handler =>
    {
        QuoteChangeEvent quoteHandler = (e) => { handler(e); }; 
        return quoteHandler;         
    },
    eh => c.OnQuoteChange += eh,
    eh => c.OnQuoteChange -= eh
);

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