What is a good way to create an IObservable for a method?

Sergey Aldoukhov picture Sergey Aldoukhov · Feb 4, 2010 · Viewed 7.3k times · Source

Let's say, we have a class:

public class Foo
{
   public string Do(int param)
   {
   }
}

I'd like to create an observable of values that are being produced by Do method. One way to do it would be to create an event which is being called from Do and use Observable.FromEvent to create the observable. But somehow I don't feel good about creation of an event just for the sake of the task. Is there a better way to do it?

Answer

Sergey Aldoukhov picture Sergey Aldoukhov · Feb 4, 2010

Matt's answer made me thinking about this:

public class Foo
{
    private readonly Subject<string> _doValues = new Subject<string>();

    public IObservable<string> DoValues { get { return _doValues; } }

    public string Do(int param)
    {
        var ret = (param * 2).ToString();
        _doValues.OnNext(ret);
        return ret;
    }
}


var foo = new Foo();
foo.DoValues.Subscribe(Console.WriteLine);
foo.Do(2);