Pat
Pat

Reputation: 16891

Create an observable that repeatedly calls a method

I would like to repeatedly get a properties value and assign it to another property, but I don't have a handle on Rx's Observable creation quite yet. How do I create and subscribe to an observable that just constantly reads a property (maybe on a timer or with throttling)?

Upvotes: 4

Views: 1203

Answers (3)

Fx Mzt
Fx Mzt

Reputation: 401

public static IObservable<long> CreateObservableTimerWithAction(this Action actionT, int timeSpan, Control control)
    {
        var obs = Observable.Create<long>(
             observer =>
             {
                 Observable.Interval(TimeSpan.FromMilliseconds(timeSpan))
.DistinctUntilChanged(fg =>control.Text ).Subscribe(l => actionT());
                 return Disposable.Empty;
             });

        return obs;
    }

0r :

public static IObservable<long> CreateObservableTimer<T>(this Action actionT,int timeSpan)
    {
       var obs= Observable.Create<long>(
            observer =>
            { 
                Observable.Interval(TimeSpan.FromMilliseconds(timeSpan))
.DistinctUntilChanged().Subscribe(l => actionT());
                return Disposable.Empty;
            });
        return obs;
    }

I use this quite often , to have timed methods go at certain time , until i dispose of them (obs.Dispose() )..

CreateObservableTimer(() => CheckForDequeues(1),500);

I actually sometimes use the long, but most of the times , not...

Even use this helper to check Schedulers in a priority queue, so could be used to

Upvotes: 1

Jim Wooley
Jim Wooley

Reputation: 10398

It sounds like you are essentially asking for a polling implementation where some component polls for changed values. Observables are typically for reacting to objects pushed to you (through events/observables/etc) rather than pulling for values. Perhaps just setting up a background process on a timer and operating on that timer's Tick would be sufficient for your case. Observable.Interval behaves similarly as James Hay mentioned. Beware that Observable.Interval will move your execution context off of the dispatcher thread.

Why are you trying to shoehorn Rx into your polling implementation? Do you have other observable data sources that you are trying to synchronize here?

Upvotes: 0

James Hay
James Hay

Reputation: 12700

You can use the static Interval operator to emit a value repeatedly on a given time span and then use a Select opertor to transform it to the property value on the object you wish to poll.

var objectIWantToPoll = new MyObject(); 
var objectIWantToSetPropertyOn = new MyObject();


var polledValues =  Observable.Interval(TimeSpan.FromSeconds(1)) 
   .Select(_ => objectIWantToPoll.SomeProperty);

polledValues.Subscribe(propertyValue => 
   objectIWantToSetPropertyOn.SomeProperty = propertyValue));

Upvotes: 9

Related Questions