I have tried using System.Reactive, but most of their merging/throttling seems to ignore the previous calls, and I can't use the OnCompleted() part of Subscribe on an event as it does not ever "complete".
I think you missed some, like the Buffer
operator:
Button button = new Button();
...
var subscription = button
.ButtonClicks()
.Buffer(TimeSpan.FromSeconds(0.5), 100) // Perform action after 100 clicks or after half a second, whatever comes first
.Select(buffer => buffer.Count)
.Subscribe(clickCount =>
{
// Do something with clickCount
})
The helper class:
public static class Extensions
{
public static IObservable<EventPattern<RoutedEventArgs>> ButtonClicks(this Button control)
{
return Observable.FromEventPattern<RoutedEventHandler, RoutedEventArgs>(
h => control.Click += h,
h => control.Click -= h);
}
}
At the end of the application:
subscription.Dispose();
Of course Buffer has some overloads:
Buffer(TimeSpan.FromSeconds(1))
-> Buffer for a second, then perform action (Same result as the accepted answer)
Buffer(100)
-> Perform action after 100 clicks