using mbts; using System.Reactive.Subjects; using System.Threading; using System.Threading.Tasks; namespace System.Reactive.Linq { public static class ObservableExtensions { /// /// 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 BufferLatest(this IObservable source, TimeSpan throttle) => source.Buffer(throttle).Where(vals => vals.Count > 0).Select(vals => vals[vals.Count - 1]); public static IObservable<(T1, T2)> CombineLatest(this IObservable source, IObservable second) => source.CombineLatest(second, (v1, v2) => (v1, v2)); public static async Task<(T result, bool success)> FirstAsyncTask(this IObservable source, TimeSpan timeout) where T : class => await source.Select(val => (val, true)).Merge(Observable.Return((default(T), false)).Delay(timeout)).FirstAsync(); public static async Task<(T result, bool success)> FirstAsyncTask(this IObservable source, Func predicate, TimeSpan timeout) where T : class => await source.Where(predicate).Select(val => (val, true)).Merge(Observable.Return((default(T), false)).Delay(timeout)).FirstAsync(); public static async Task<(TResult result, bool success)> FirstAsyncTask(this IObservable source, Func predicate, Func selector, TimeSpan timeout) where T : class => await source.Where(predicate).Select(val => (selector(val), true)).Merge(Observable.Return((default(TResult), false)).Delay(timeout)).FirstAsync(); /// /// 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<(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 SelectManyInSeries(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.Select(v => v).Subscribe(on_source); return Disposable.Create(dispose); // local methods void on_source(T value) => Disposable.replace(ref value_sub, subscribe_value(value)); void dispose() { Disposable.dispose(ref source_sub); Disposable.dispose(ref value_sub); } } // 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); } }