Benjol
Benjol

Reputation: 66579

Throttled async polling with Observable

Maybe I'm pushing the bounds of what is reasonable for Rx here, but what I'm trying to do is poll a remote status, but rate limit the polling to something reasonable.

Pseudo code for what I currently have:

IObservable<data> RemoteObservable(Remote remote) 
{
   var onceonly = Observable.FromAsyncPattern(remote.Begin, remote.End);
   return Observable.Defer(() => onceonly())
                    .ObserveOn(Scheduler.ThreadPool)
                    .Repeat();
}

I can't work out whether using Throttle or Interval in there might help. In my mind throttling is about limiting the incoming events, not limiting the Repeat rate.


EDIT: I asked/answered a separate question about the subquestion below: How to make a `Defer`ed observable only subscribe for the first subscriber?.

Sub-question: is there a way to permit two subscriptions on this kind of Observable, without that creating twice as many calls to remote? I ask because I'd like to display the status continually in the UI, but also monitor it during some activities (one of the reasons I'm trying to do this with Observables).

Upvotes: 0

Views: 610

Answers (3)

Ana Betts
Ana Betts

Reputation: 74662

How about:

var onceOnly = Observable.FromAsyncPattern(remote.Begin, remote.End);

Observable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(5))
    .SelectMany(_ => onceOnly());

Upvotes: 1

Benjol
Benjol

Reputation: 66579

I managed to track down a similar question here, with which an updated example of my code looks like this:

return Observable.Defer(() => onceonly())
                 .ObserveOn(Scheduler.ThreadPool)
                 .Concat(Observable.Empty<data>().Delay(TimeSpan.FromSeconds(5)))
                 .Repeat();

This appears to work.

(However I've discovered that my remote object would need to be reinstantiated on every call to FromAsyncPattern. Not sure how I can Repeat that)

Upvotes: 0

JonnyRaa
JonnyRaa

Reputation: 8038

For the subquestion it sounds like you could have one thing listening to that object's events (Im not familiar with Observables so not sure how that works) and then have that thing firing its own event which you could subscribe to multiple times.

Upvotes: 0

Related Questions