namespace Spark.Core.Reactive { using Spark.Core.Disposables; using Spark.Core.Reactive; using System; using System.Reactive; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading; using System.Threading.Tasks; public static class ObservableExtensions { public static IObservable And(this IObservable source1, IObservable source2) => source1.CombineLatest(source2).Select(tup => tup.Item1 && tup.Item2); /// /// Creates an "Observable Heartbeat" that will publish true/false to indicate whether or not the heartbeat is detected, it will only send updates when the 'heartbeat status' has changed. /// Whenever the source produces an update, the heartbeat evaluates to true and the heartbeat duration clock is reset. /// Whenever heartbeat duration clock expires, the heartbeat evaluates to false. /// /// Type of data produced by the source (bears no impact on the resultant observable heartbeat /// The source that will indicate alive/dead by publishing updates within the duration period /// The amount of time that must pass without receiving an update from the source to determine the heartbeat is not detected /// An "Observable Heartbeat" public static IObservable AsHeartbeat(this IObservable source, TimeSpan duration) { IObservable dead = source.Throttle(duration).Select(_ => false); IObservable alive = source.Select(_ => true); return dead.Merge(alive).DistinctUntilChanged(); } public static IObservable Bootstrap(this IObservable source, Func bootstrap_selector) => source.Bootstrap(bootstrap_selector, _ => _); public static IObservable Bootstrap( this IObservable source, Func bootstrap_selector, Func selector) => Observable.Create(o => { object locker = new(); return source.Subscribe(v => { // The preliminary null-check for `bootstrapper` is performed outside of the lock. // // If `bootstrapper is null`, the observer has already been bootstrapped. This is // known with certainty because, once assigned null, `bootstrapper` is never // reassigned. All notifications from hence-forth are forwarded directly to the // observer. // // If `bootstrapper is not null`, the use of a lock becomes neccessary to ensure that // the observer is only bootstrapped once. if (bootstrap_selector is null) { o.OnNext(selector(v)); return; } lock (locker) { o.OnNext((bootstrap_selector ?? selector)(v)); bootstrap_selector = null; } }); }); public static IObservable BufferLatest(this IObservable source, TimeSpan throttle) => source.Buffer(throttle).Where(vals => vals.Count > 0).Select(vals => vals[vals.Count - 1]); public static async Task<(T result, bool success)> FirstAsyncTask( this IObservable source, TimeSpan timeout, T default_value = default) => await source .Select(val => (val, true)) .Merge(Observable.Return((default_value, false)).Delay(timeout)) .FirstAsync(); public static async Task<(T result, bool success)> FirstAsyncTask( this IObservable source, Func predicate, TimeSpan timeout, T default_value = default) => await source.Where(predicate) .Select(val => (val, true)) .Merge(Observable.Return((default_value, false)).Delay(timeout)) .FirstAsync(); public static async Task<(TResult result, bool success)> FirstAsyncTask( this IObservable source, Func predicate, Func selector, TimeSpan timeout, TResult default_value = default) => await source.Where(predicate) .Select(val => (selector(val), true)) .Merge(Observable.Return((default_value, false)).Delay(timeout)) .FirstAsync(); public static IObservable FlattenSeries( this IObservable> outer_source, Func bridge) { return Observable.Create(o => { T last_val = default; bool is_first_outer = true; IDisposable inner_sub = null; var outer_sub = outer_source.Subscribe(on_new_source); return Disposable.Create(dispose); void on_new_source(IObservable source) { inner_sub?.Dispose(); bool is_first_inner = true; inner_sub = source.Subscribe(on_next); void on_next(T value) { if (is_first_inner.toggle_to(false) && !is_first_outer.toggle_to(false)) { // Bridge the new value with the last one received from the previous source. value = bridge(last_val, value); } o.OnNext(value); } } void dispose() { outer_sub.Dispose(); inner_sub?.Dispose(); } }); } /// /// A less verbose way to call . /// public static IObservable FromAction(Action event_source) => Observable.FromEvent, T>(cb => event_source += cb, cb => event_source -= cb); public static IObservable FromEvent(Action add_handler, Action remove_handler, Func selector) => Observable.Create(o => { callback(); add_handler(callback); return Disposable.Create(() => remove_handler(callback)); 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); public static IObservable<(TSource prev, TSource curr)> PairWithPrevious(this IObservable source, TSource default_value) => source.Scan((default_value, default_value), (last, next) => (last.curr, next)); public static IObservable RefCountReplay(this IObservable source, int buffer_size) { if (buffer_size < 0) throw new ArgumentException("Buffer size is less than zero.", nameof(buffer_size)); if (buffer_size == 0) return source.Publish().RefCount(); int num_subscribers = 0; ReplaySubject replay = new ReplaySubject(buffer_size); IDisposable source_sub = null; return Observable.Create(o => { if (Interlocked.Increment(ref num_subscribers) == 1) source_sub = source.Subscribe(replay.OnNext); IDisposable sub = replay.Subscribe(o); return Disposable.Create(() => { sub.Dispose(); if (Interlocked.Decrement(ref num_subscribers) == 0) source_sub.Dispose(); }); }); } /// /// Uses each element of a source observable to create an inner observable of , unlike , /// each inner sequence is terminated when the next one begins. /// In other words, observers are notified by the inner observerables in "series," rather than "parallel." /// /// The type of elements in the source (outer) sequence. /// The type of elements in the inner sequences. /// A sequence of elements to create a series of inner sequences. /// A function to create an inner sequence. /// An IDisposable object used to unsubscribe from the source (outer) sequence, and the latest inner sequence. public static IObservable SelectSeries(this IObservable source, Func> select_next) => Observable.Create(o => { object locker = new object(); bool is_disposed = false; IDisposable inner_sub = null; IDisposable outer_sub = source.Subscribe(on_outer); return Disposable.Create(dispose); // local methods void on_outer(TSource value) { lock (locker) { if (!is_disposed) { inner_sub?.Dispose(); inner_sub = select_next(value)?.Subscribe(o.OnNext); } } } void dispose() { IDisposable temp_outer_sub = null, temp_inner_sub = null; lock (locker) { is_disposed = true; temp_outer_sub = outer_sub; outer_sub = null; temp_inner_sub = inner_sub; inner_sub = null; } temp_outer_sub?.Dispose(); temp_inner_sub?.Dispose(); } }); public static IObservable StartWith(this IObservable source, Func get_value) => Observable.Create(o => { o.OnNext(get_value()); return source.Subscribe(o); }); public static IObservable StartWith(this IObservable source, Func get_value, Func can_get_value) => Observable.Create(o => { if (can_get_value()) o.OnNext(get_value()); return source.Subscribe(o); }); public static IDisposable Subscribe(this IObservable source, params IObserver[] observers) { return source.Subscribe(on_next, on_error, on_completed); // local methods void on_next(T value) { for (int i = 0; i < observers.Length; i++) observers[i].OnNext(value); } void on_error(Exception error) { for (int i = 0; i < observers.Length; i++) observers[i].OnError(error); } void on_completed() { for (int i = 0; i < observers.Length; i++) observers[i].OnCompleted(); } } /// /// An inner subscription is made for each value in the source sequence using the specified delegate (). /// When a new value arrives, the subscription for the previous value is disposed before is invoked with the new value. /// /// The type of elements in the source sequence. /// A sequence of elements to invoke a subscribe function on. /// A function used to subscribe each source element. /// An IDisposable object used to unsubscribe from the source sequence, and dispose the latest value subscription. public static IDisposable SubscribeEach(this IObservable source, Func subscribe_value) { IDisposable value_sub = null; IDisposable source_sub = source.Subscribe(on_source); return Disposable.Create(dispose); // local methods void on_source(T value) { Disposable.dispose(ref value_sub); value_sub = subscribe_value(value); } void dispose() { Disposable.dispose(ref source_sub); Disposable.dispose(ref value_sub); } } public static ConnectableObservableAdaptor ToObservable( this IConnectableObservable source) => new(source); // was sick of this scenario: observable_source.Select(enumerable => enumerable.FirstOrDefault(where)).Where(val => val != null) // with structs it was even more annoying because they can't be null public static IObservable TrySelect(this IObservable source, Func try_select) => source.Select(try_select).Where(ts => ts.success).Select(ts => ts.result); public static IObservable StopAfter(this IObservable source, TimeSpan duration) { return Observable.Create(o => { int state = 0; IDisposable sub = null; sub = source.Subscribe(new AnonymousObserver(o.OnNext, o.OnError, on_complete)); stop_async(); return Disposable.Create(dispose); async void stop_async() { await Task.Delay(duration); on_complete(); } void on_complete() { if (Interlocked.Increment(ref state) == 1) { o.OnCompleted(); Disposable.dispose(ref sub); } } void dispose() { if (Interlocked.Increment(ref state) == 1) { Disposable.dispose(ref sub); } } }); } public static IObservable WhereValues(this IObservable source) where T : struct => Observable.Create(o => source.Subscribe(v => { if (v.HasValue) { o.OnNext(v.Value); } })); } }