Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 905
Pat Avatar asked Dec 28 '22 21:12

Pat


2 Answers

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));
like image 150
James Hay Avatar answered Jan 11 '23 21:01

James Hay


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

like image 45
Fx Mzt Avatar answered Jan 11 '23 21:01

Fx Mzt