从这个答案中可以看出:
https://stackoverflow.com/a/46629909/377562
BufferWithClosingValue
从链接的答案中:
public static IObservable<IList<TSource>> BufferWithClosingValue<TSource>(
this IObservable<TSource> source,
TimeSpan maxTime,
TSource closingValue)
{
return source.GroupByUntil(_ => true,
g => g.Where(i => i.Equals(closingValue)).Select(_ => Unit.Default)
.Merge(Observable.Timer(maxTime).Select(_ => Unit.Default)))
.SelectMany(i => i.ToList());
}
随机序列示例:
var alternatingTrueFalse = Observable.Generate(
true,
_ => true,
x => !x,
x => x,
_ => TimeSpan.FromMilliseconds(new Random().Next(1000)))
.Take(40).Publish().RefCount();
var bufferedWithTime = alternatingTrueFalse.BufferWithClosingValue(TimeSpan.FromMilliseconds(500), false);
var clicks = bufferedWithTime.Where(x => x.Count() == 2).ThrottleFirst(TimeSpan.FromMilliseconds(500));
var holdStarts = bufferedWithTime.Where(x => x.Count() == 1 && x.First() == true);
var holdStops = bufferedWithTime.Where(x => x.Count() == 1 && x.First() == false);
clicks.Select(_ => "Click").DumpTimes("Clicks");
holdStarts.Select(_ => "Hold Start").DumpTimes("Hold Start");
holdStops.Select(_ => "Hold Stop").DumpTimes("Hold stop");
ThrottleFirst
SampleFirst
此答案的实现:
https://stackoverflow.com/a/27160392/377562
示例输出
2017-10-08 16:58:14.549 - Hold Start-->Hold Start :: 6
2017-10-08 16:58:15.032 - Hold stop-->Hold Stop :: 7
2017-10-08 16:58:15.796 - Clicks-->Click :: 7
2017-10-08 16:58:16.548 - Clicks-->Click :: 6
2017-10-08 16:58:17.785 - Hold Start-->Hold Start :: 5
2017-10-08 16:58:18.254 - Hold stop-->Hold Stop :: 7
2017-10-08 16:58:19.294 - Hold Start-->Hold Start :: 8
2017-10-08 16:58:19.728 - Hold stop-->Hold Stop :: 7
2017-10-08 16:58:20.186 - Clicks-->Click :: 6
这似乎没有任何比赛条件的问题,我已经与其他一些试图解决这个问题,所以我喜欢它!