Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 203
Sergey Aldoukhov Avatar asked Feb 04 '10 04:02

Sergey Aldoukhov


People also ask

How do you make a observable method?

You can use Observable. defer instead. It accepts a function that returns an Observable or an Observable-like thing (read: Promise, Array, Iterators).

How many ways can you make observable?

There are two main methods to create Observables in RxJS. Subjects and Operators. We will take a look at both of these!


1 Answers

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);
like image 54
Sergey Aldoukhov Avatar answered Oct 05 '22 23:10

Sergey Aldoukhov