Search code examples
c#observablesystem.reactivereactiveobserver-pattern

Observable from Func delegate


Is there a method or library function that would accept Func<T> and return IObservable<T> by invoking it?

The functionality should be probably equal to

public IObservable<T> Create<T>(Func<T> factory){
  try{
    return Observable.Return(factory());
  }
  catch(Exception ex){
    return Observable.Throw<T>(ex);
  }
}

Seems like a lot of code for something so simple. Is there something out of the box?

I checked Observable.Return, Observable.Generate and some others, but could not find anything that would accept Func<T> delegate.


Solution

  • You can use the Observable.Start() method to create an observable from a Func<> like this:

    Func<int> func = () => Random.Shared.Next();
    
    IObservable<int> obs = Observable.Start(func);
    
    obs.Subscribe(it => Console.WriteLine(it));