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

后端 未结 5 2017
攒了一身酷
攒了一身酷 2021-02-05 11:30

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

5条回答
  •  醉酒成梦
    2021-02-05 12:02

    I'm assuming you control the Foo class, since you're talking about adding an event to it as one option. Since you own the class, is there any reason you can't define your own IObservable implementation for the Do method?

    public class Foo
    {
        DoObservable _doValues = new DoObservable();
    
        public IObservable DoValues
        {
            return _doValues;
        }
    
        public string Do(int param)
        {
            string result;
            // whatever
            _doValues.Notify(result);
        }
    }
    
    public class DoObservable : IObservable
    {
        List> _observers = new List>();
    
        public void Notify(string s)
        {
            foreach (var obs in _observers) obs.OnNext(s);
        }
    
        public IObserver Subscribe(IObserver observer)
        {
            _observers.Add(observer);
            return observer;
        }
    }
    

    Your class now has an Observable property which provides a way to subscribe to the values returned from the Do method:

    public class StringWriter : IObserver
    {
        public void OnNext(string value)
        {
            Console.WriteLine("Do returned " + value);
        }
    
        // and the other IObserver methods
    }
    
    var subscriber = myFooInstance.DoValues.Subscribe(new StringWriter());
    // from now on, anytime myFooInstance.Do() is called, the value it 
    // returns will be written to the console by the StringWriter observer.
    

    I've not dabbled too much into the reactive framework, but I think this is close to how you would do this.

提交回复
热议问题