I have a sequence of true false values like so
var alternatingTrueFalse = Observable.Generate(
true,
_ => true,
x => !x,
x => x,
_ => TimeSpan.FromMilliseconds(new Random().Next(2000)))
.Take(20).Publish();
alternatingTrueFalse.Connect();
var buffered = alternatingTrueFalse
.Buffer(TimeSpan.FromMilliseconds(500))
.Subscribe(x => Console.WriteLine($"{TimeStamp} {string.Join(",", x)}"));
I want to look at the sequence in terms of 500 ms (max) windows / buffers. If there is only one true value (and nothing else) inside one such window, I want to flip a switch (just call a command, print to console for now). Then, when the next false value arrives, I want to flip the switch back and close the current window / buffer of the original sequence and start a new one.
Using Buffer + Scan to flip the switch
So far I've come up with a way to do this on a Buffer, with this. However, the buffers are open too long, they are always 500 ms.
var buffered = alternatingTrueFalse
.Buffer(TimeSpan.FromMilliseconds(500));
var output = buffered
.Subscribe(x => Console.WriteLine($"{TimeStamp} {string.Join(",", x)}"));
var isFlipped = buffered.Scan(false,
(x, y) =>
{
if (y.Count == 0)
{
return x;
}
return y.Count == 1 && y.First();
});
isFlipped.DumpTimes("Flipped");
I'm trying to figure out how to use Window instead of Buffer to be able to flip the switch back on the first false after an isolated true. But I can't seem to get it right, I'm not quite fluent in Rx yet and not sure how to use the windowOpening / Closing values for it.
Example output
original
2017-10-07 20:21:39.302 True,False // Rapid values should not flip the switch (actually they should flip a different switch)
2017-10-07 20:21:39.797 True // Flip the switch here
2017-10-07 20:21:40.302 False // Flip the switch back and close the current window
2017-10-07 20:21:40.797 True // Flip the switch here
2017-10-07 20:21:41.297
2017-10-07 20:21:41.798 False // Etc...
...
2017-10-07 20:21:43.297 True
2017-10-07 20:21:43.800 False,True // Example of a window that is open too long, because it is not closed immediately upon the false value
...
buffer + scan
2017-10-07 20:47:15.154 True
2017-10-07 20:47:15.163 - Flipped-->True
2017-10-07 20:47:15.659 False,True // Example of a window open too long
2017-10-07 20:47:15.661 - Flipped-->False