I’m new to RX but feel it should be able to provide a good solution to a task I wish to solve. After quite a bit of searching I still haven’t found a solution.
I have a WPF application within which a control does some work in response to some mouse move events. I would like to reduce the frequency of the events, so that the handler gets called less frequently than is currently the case (as the user moves the mouse across the control). Ideally, what I want is to set up and subscribe to an observer. The observer should observe the mouse move events and call the client code with the most recent event and arguments after a particular time window has elapsed, say 0.2s. Being new to RX, I first replaced my original standard event hook-up with an observer as follows:
var mouseMove = Observable.FromEventPattern<MouseEventArgs>(myControl, "MouseMove");
mouseMove.Subscribe(args => myControl_MouseMove(args.Sender, args.EventArgs));
This seemed to work fine.
I then attempted to modify the observer to get the behaviour I described above. I tried using the Throttle() call and the Sample() call. These didn’t produce the outcome I expected (or desire). In fact in certain cases using a particular overload of the Throttle/TimeSpan call killed my application dead, which still I don’t understand.
This is an example of what I’ve tried:
var mouseMove = Observable.FromEventPattern<MouseEventArgs>(myControl, "MouseMove").Throttle(TimeSpan.FromSeconds(0.2));
mouseMove.Subscribe(args => myControl_MouseMove(args.Sender, args.EventArgs));
From reading, Throttle appears to swallow events until the frequency drops below a particular threshold (not quite what I expected), whereas I believe Sample samples the observed events at a regular interval? I would like the client code to be given the most recent event in a given time interval. If no events have been recorded in that interval, then the client should not be called.
Hope someone can help an RX newbie on this.
Oh, I also want to be kept informed of the (reduced frequency) mouse moves for the duration of the control’s lifetime.
Max
I think you’re on the right track with
Sample– what, specifically, did this not do for you?Example LINQPad snippet: