Using Rx, accept the last activated event every 60 seconds

I have an event that fires (potentially) every second (timer mark). What I would like to do is use the latest EventArgs every 60 seconds (if there were new ticks during these 60 seconds). I tried to do something like:

 Observable.FromEventPattern( h => myThing.SomeEvent += h, h => myThing.SomeEvent -= h) .Throttle(TimeSpan.FromSeconds(60)) .TakeLast(1) .Do(p => // do something with p); 

Unfortunately, I never get to the Do method, and I'm not sure what I am doing wrong?

Sorry if this is completely wrong, I first used Rx :)

Edit: In the sentences below, I changed Do to Subscribe , but I still don't get any results if I use Throttle . Should I use it at all?

+4
source share
4 answers

I think this is already designed, you just need to use Sample , it does exactly what you want:

 source.Sample(TimeSpan.FromSeconds(60)).Subscribe(x => /* .. */); 
+10
source

Do it:

 Observable.FromEventPattern(h => myThing.SomeEvent += h, h => myThing.SomeEvent -= h) .Window(TimeSpan.FromSeconds(60)) .SelectMany(x => x.TakeLast()) .Subscribe(x => /* ... */); 
+7
source

Given this snippet, nothing will happen until you subscribe to the Observed. IIRC, the event only connects when someone calls to "Subscribe" (he is not connected to the network when disconnecting the subscription).

I try to avoid using Do. Observable is a stream of values, and you should really handle these values ​​(and stream termination or erroneous) using the methods passed during the subscription. Then it becomes a side effect - something that you do, like whiz values ​​on the way to the OnNext method.

+3
source

Well Throttle will not solve the problem because ..

The way the throttle works is that it waits for a pause for a given period of time, say, you get an event every second, and your Throttle - 1 minute, you will never see anything. If something does not happen to your flow, and suddenly there is a pause for more than 1 minute.

One of the most used examples for Throttle uses it for an autocomplete window, where you do not want to run a filter list request every time you press a key, so you set the throttle to say 300 ms, so someday the user will stop typing, at least on 300 ms you will shoot on search.

I wonder if your decision can benefit from a buffer or a window ... I'm sure Paul can understand something even more amazing than my brain at the moment. Do not use Rx a lot for several months :(

+2
source

All Articles