diff --git a/src/client/spark_core/utils/ObservableExtensions.cs b/src/client/spark_core/utils/ObservableExtensions.cs index eabf174a6..8544f29d0 100644 --- a/src/client/spark_core/utils/ObservableExtensions.cs +++ b/src/client/spark_core/utils/ObservableExtensions.cs @@ -49,6 +49,62 @@ namespace System.Reactive.Linq { void callback() => o.OnNext(selector()); }); + public static IObservable FromEventThrottle(Action> add_handler, Action> remove_handler, TimeSpan throttle) => + FromEventThrottle(cb => { + add_handler(cb); + return Disposable.Create(() => remove_handler(cb)); + }, throttle); + + public static IObservable FromEventThrottle(Func, IDisposable> add_handler, TimeSpan throttle) => + Observable.Create(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 FromEventThrottle(Action> add_handler, Action> remove_handler, Func selector, TimeSpan throttle) => + FromEventThrottle(cb => { + add_handler(cb); + return Disposable.Create(() => remove_handler(cb)); + }, selector, throttle); + + public static IObservable FromEventThrottle(Func, IDisposable> add_handler, Func selector, TimeSpan throttle) => + Observable.Create(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(this IObservable source) => PairWithPrevious(source, default);