Throttle method skips values from an observable sequence if others follow too quickly. But I need a method to just delay them. That is, I need to set a minimum delay between items, without skipping any.
Practical example: there’s a web service which can accept requests no faster than once a second; there’s a user who can add requests, single or in batches. Without Rx, I’ll create a list and a timer. When users adds requests, I’ll add them to the list. In the timer event, I’ll check wether the list is empty. If it is not, I’ll send a request and remove the corresponding item. With locks and all that stuff. Now, with Rx, I can create Subject, add items when users adds requests. But I need a way to make sure the web service is not flooded by applying delays.
I’m new to Rx, so maybe I’m missing something obvious.
There’s a fairly easy way to do what you want using an
EventLoopScheduler.I started out with an observable that will randomly produce values once every 0 to 3 seconds.
Now, to make this output values immediately unless the last value was within a second ago I did this:
This effectively observes the source on the
EventLoopSchedulerand then puts it to sleep for 1 second after eachOnNextso that it can only begin the nextOnNextafter it wakes up.I tested that it worked with this code:
I hope this helps.