-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObservableExtensions.cs
More file actions
75 lines (68 loc) · 2.76 KB
/
Copy pathObservableExtensions.cs
File metadata and controls
75 lines (68 loc) · 2.76 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
64
65
66
67
68
69
70
71
72
73
74
75
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
namespace CodeCasa.AutomationPipelines.Lights.Extensions;
internal static class ObservableExtensions
{
public static IObservable<Unit> ToPulsesWhenTrue(this IObservable<bool> source, TimeSpan timeBetweenPulses, IScheduler scheduler)
{
return source
.Select(b =>
b
? Observable.Timer(TimeSpan.Zero, timeBetweenPulses, scheduler).Select(_ => Unit.Default)
: Observable.Empty<Unit>())
.Switch();
}
public static IObservable<TValue> ToCycleObservable<TTrigger, TValue>(
this IObservable<TTrigger> triggerObservable,
IEnumerable<(Func<TValue> valueFactory, Func<bool> valueIsActiveFunc)> cycleValues)
{
var cycleValuesList = cycleValues.ToList();
return triggerObservable.Select(_ =>
{
var index = cycleValuesList.FindIndex(n => n.valueIsActiveFunc()) + 1;
if (index >= cycleValuesList.Count)
{
index = 0;
}
return cycleValuesList[index].valueFactory();
});
}
public static IObservable<TValue?> ToToggleObservable<TTrigger, TValue>(
this IObservable<TTrigger> triggerObservable,
Func<DateTime?, bool> offCondition,
Func<TValue> offValueFactory,
IEnumerable<Func<TValue>> valueFactories,
TimeSpan timeout,
bool? includeOff)
{
var valueFactoryArray = valueFactories.ToArray();
var includeOffBool = includeOff ?? valueFactoryArray.Length <= 1;
if (!includeOffBool && valueFactoryArray.Length <= 1)
{
throw new InvalidOperationException("When only supplying one factory, off should be included.");
}
DateTime? previousLastChanged = null;
var index = 0;
var maxIndexValue = includeOffBool ? valueFactoryArray.Length : valueFactoryArray.Length - 1;
return triggerObservable
.Select(_ =>
{
var utcNow = DateTime.UtcNow;
var consecutive = previousLastChanged != null && utcNow - previousLastChanged < timeout;
if (!consecutive)
{
index = 0;
if (offCondition(previousLastChanged))
{
previousLastChanged = utcNow;
return offValueFactory();
}
}
var value = index >= valueFactoryArray.Length ? offValueFactory() : valueFactoryArray[index]();
index = index < maxIndexValue ? index + 1 : 0;
previousLastChanged = utcNow;
return value;
});
}
}