开发者

Need help with RX:Convert System.Diagnostics.Process.OutputDataReceived to an Observable

I want to start a subprocess and watch it's redirected out开发者_开发问答put. That not a problem for me in C#, but I try to understand RX, so the game begins ... I have a static extension method for process, which looks like this:

    public static IObservable<IEvent<DataReceivedEventArgs>> GetOutput(this Process that)
    {
        return Observable.FromEvent<DataReceivedEventArgs>(that, "OutputDataReceived");
    }

I create an observable and subscribe to it like this:

    Process p = ........
    var outObs = p.GetOutput();
    var outSub = outObs.Subscribe(data => Console.WriteLine(data));

This is not completely wrong, but I am getting:

System.Collections.Generic.Event`1[System.Diagnostics.DataReceivedEventArgs]

while I am expecting to get strings :-(

So, I think, my extensionmethod returns the wrong type. It would be really good, if someone could explain me, what's wong with my extension methods signature.

Thanks a lot, ++mabra


So, I think, my extensionmethod returns the wrong type

That's exactly it.

IEvent wraps both the sender and the EventArgs parameters of a tradition Event delegate. So you need to modify your code to look something like

public static IObservable<string> GetOutput(this Process that)
{
    return Observable.FromEvent<DataReceivedEventArgs>(that, "OutputDataReceived")
                     .Select(ep => ep.EventArgs.Data);
}

If you're using the latest Rx, then the code is a bit different

public static IObservable<string> GetOutput(this Process that)
{
       return Observable.FromEventPattern<DataReceivedEventArgs>(that, "OutputDataReceived")
                        .Select(ep => ep.EventArgs.Data);
}

the key here is to Select the EventArgs from the EventPattern/IEvent, and then grab the Data

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜