-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtility.cs
More file actions
63 lines (56 loc) · 1.55 KB
/
Utility.cs
File metadata and controls
63 lines (56 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System.Diagnostics;
using System.Reactive.Disposables;
using System.Reactive.Linq;
namespace NodeDev.Blazor;
public static class Utility
{
public static IObservable<T> AcceptThenSample<T>(this IObservable<T> source, TimeSpan interval)
{
return Observable.Create<T>(o =>
{
var stopwatch = new Stopwatch();
T lastReceived = default!;
bool isTimerRunning = false;
var timer = new Timer(_ =>
{
o.OnNext(lastReceived);
isTimerRunning = false; // timer is done, so we can start a new one
lastReceived = default!; // clear the cache
stopwatch.Restart();
});
var sub = source.Subscribe(x =>
{
if (!stopwatch.IsRunning || (stopwatch.Elapsed > interval && !isTimerRunning)) // either the first time or it's been a while since the last time
{
o.OnNext(x); // send the value away
stopwatch.Restart(); // start the timer since the last time we sent a value
}
else if (stopwatch.Elapsed < interval) // it's not been long enough, cache the value and start a timer to send if nothing else comes in
{
lastReceived = x;
if (!isTimerRunning)
{
isTimerRunning = true;
timer.Change(interval - stopwatch.Elapsed, Timeout.InfiniteTimeSpan); // Start a timer for the remaining time, with no repeat
}
}
}, ex =>
{
timer?.Dispose();
timer = null!;
o.OnError(ex);
}, () =>
{
timer?.Dispose();
timer = null!;
o.OnCompleted();
});
return Disposable.Create(() =>
{
timer?.Dispose();
timer = null!;
sub.Dispose();
});
});
}
}