added 'FromEventThrottle()' to ObservableExtensions

This commit is contained in:
John Colvin committed 2019-08-19 13:14:58 -05:00
1 parent 1b48739e1e
commit 0fcdf3f4ff
1 file changed
+56
@@ -49,6 +49,62 @@ namespace System.Reactive.Linq {
void callback() => o.OnNext(selector());
});
public static IObservable<T> FromEventThrottle<T>(Action<Action<T>> add_handler, Action<Action<T>> remove_handler, TimeSpan throttle) =>
FromEventThrottle<T>(cb => {
add_handler(cb);
return Disposable.Create(() => remove_handler(cb));
}, throttle);
public static IObservable<T> FromEventThrottle<T>(Func<Action<T>, IDisposable> add_handler, TimeSpan throttle) =>
Observable.Create<T>(o => {
T last_value = default;
bool busy = false, dirty = false;
return add_handler(callback);
async void callback(T value) {
last_value = value;
if (busy) {
dirty = true;
} else {
busy = true;
do {
dirty = false;
o.OnNext(last_value);
await Task.Delay(throttle);
} while (dirty);
busy = false;
}
}
});
public static IObservable<TResult> FromEventThrottle<T, TResult>(Action<Action<T>> add_handler, Action<Action<T>> remove_handler, Func<T, TResult> selector, TimeSpan throttle) =>
FromEventThrottle(cb => {
add_handler(cb);
return Disposable.Create(() => remove_handler(cb));
}, selector, throttle);
public static IObservable<TResult> FromEventThrottle<T, TResult>(Func<Action<T>, IDisposable> add_handler, Func<T, TResult> selector, TimeSpan throttle) =>
Observable.Create<TResult>(o => {
T last_value = default;
bool busy = false, dirty = false;
return add_handler(callback);
async void callback(T value) {
last_value = value;
if (busy) {
dirty = true;
} else {
busy = true;
do {
var result = selector(last_value);
dirty = false;
o.OnNext(result);
await Task.Delay(throttle);
} while (dirty);
busy = false;
}
}
});
public static IObservable<(TSource prev, TSource curr)> PairWithPrevious<TSource>(this IObservable<TSource> source) =>
PairWithPrevious(source, default);