diff --git a/src/client/spark/Admin/AdminModel.cs b/src/client/spark/Admin/AdminModel.cs index 77a6829d6..6ba429faf 100644 --- a/src/client/spark/Admin/AdminModel.cs +++ b/src/client/spark/Admin/AdminModel.cs @@ -1,24 +1,33 @@ using bts; +using bts.admin.risk; +using bts.api; using bts.api.admin; using bts.api.core; +using bts.spark; using bts.utils; using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Linq; using System.Reactive.Linq; +using System.Threading.Tasks; namespace mbts.spark { [Export] class AdminModel : IDisposable { public readonly UserTuple user; + readonly AdminService _service; + readonly ErrorReporter _error_reporter; IDisposable _dispose; IReadOnlyDictionary _account_map = DictionaryHelper.empty(); [ImportingConstructor] - AdminModel(AdminService service, UserTuple user) { + AdminModel(AdminService service, UserTuple user, SecurityStore security_store, ErrorReporter error_reporter) { this.user = user; + _service = service; + _error_reporter = error_reporter; // accounts on_accounts = service.subscribei_admin_data() .Select(up => up.all.TryGetFirst(out var ad) && ad.Users.Where(u => u.Name == user.name).TryGetSingle(out var usr) && usr.HasUserData && usr.UserData.HasAccountPermissions ? @@ -31,6 +40,34 @@ namespace mbts.spark { new Dictionary(0)) .Replay(1) .RefCount(); + // account risk limits + account_security_risk_limits = service.subscribei_admin_data().Where(ad => ad.all.Any()) + .Select(upd => { + AdminDataImmutable admin_data = upd.all.First(); + return admin_data.Accounts.SelectMany(acc => + (acc.HasProprietaryRiskLimits ? acc.ProprietaryRiskLimits.SecurityLimits : Enumerable.Empty()) + .Select(api_limit => AccountSecurityRiskLimitsDataHelper.to_client_data(acc.Id, api_limit))) + .ToDictionary(AccountSecurityRiskLimitsDataHelper.key_fn); + }) + .Table(AccountSecurityRiskLimitsDataHelper.key_fn); + // this isn't the most efficient join, but the SecurityStore join is more complex than a simple + // left join operation, because missing securities are retrieved asynchronously, then merged back into the output sequence. + // Until it is known that this inefficiency is problematic, best to leave the battle-tested SecurityStore code alone. + account_security_risk_limits = security_store.join< + TableUpdate, + AccountSecurityRiskLimits, + AccountSecurityKey, + TableUpdate>(account_security_risk_limits, + cli_lim => cli_lim.security_key, + table => (table.state.Values, table.added, table.changes, table.removed, AccountSecurityRiskLimitsDataHelper.key_fn), + (all, added, changes, removed, key_fn) => + new TableUpdate( + ImmutableDictionary.CreateRange( + all.Select(tup => new KeyValuePair(tup.val.key, risk_lim_with_sec(tup)))), + added.Select(risk_lim_with_sec), + changes.Select(ch => new Change(risk_lim_with_sec(ch.Old), risk_lim_with_sec(ch.New))), + removed.Select(risk_lim_with_sec), + AccountSecurityRiskLimitsDataHelper.key_fn)); // users on_users = Observable.Return(DictionaryHelper.wrap_value(user.id, user.name)); all_user_tuples = user.permissions == UserTuple.Permissions.Admin ? @@ -45,12 +82,16 @@ namespace mbts.spark { .Cache() : Observable.Return(TableUpdate.mk_empty(UserTuple.key_fn).with_added(new[] { user })); _dispose = on_accounts.Subscribe(map => _account_map = map); + // local methods + AccountSecurityRiskLimits risk_lim_with_sec((SecurityImmutable? sec, AccountSecurityRiskLimits val) tup) => + tup.val.with(security: tup.sec); } public IObservable> on_users { get; } public IObservable> on_accounts { get; } public IObservable> all_user_tuples { get; } public IObservable> on_account_tuples => on_accounts.Select(d => d.Select(kv => new AccountTuple(kv.Key, kv.Value)).ToListSorted(a => a.name)); + public IObservable> account_security_risk_limits { get; } public IObservable> permission_filter(IObservable> positions, Func get_account_id) where TKey : IEquatable => user.permissions == UserTuple.Permissions.Admin ? @@ -68,7 +109,69 @@ namespace mbts.spark { public AccountTuple? get_default_account() => _account_map.Select(kv => new AccountTuple(kv.Key, kv.Value)).TryFirst(); + public Task<(bool success, string error_msg)> add_or_update_risk_limits(uint account_key, IEnumerable<(uint security_key, RiskLimits limits)> new_limits) { + return _modify_risk_limits("Updating Risk Limits", account_key, add_limits); + // + ProprietaryRiskLimits add_limits(ProprietaryRiskLimits prlimits) { + foreach (var (security_key, limits) in new_limits) { + var api_limits = AccountSecurityRiskLimitsDataHelper.from_client_data(security_key, limits); + if (prlimits.SecurityLimits.TryGetFirstIndex(l => l.SecurityKey == security_key, out int index)) { + prlimits.SecurityLimits[index] = api_limits; + } else { + prlimits.SecurityLimits.Add(api_limits); + } + } + return prlimits; + } + } + + public Task<(bool success, string error_msg)> delete_risk_limits(uint account_key, IEnumerable security_keys) { + return _modify_risk_limits("Deleting Risk Limits", account_key, remove_secs); + // + ProprietaryRiskLimits remove_secs(ProprietaryRiskLimits prlimits) { + var sec_key_set = new HashSet(security_keys); + for (int i = 0; i < prlimits.SecurityLimits.Count; i++) { + if (sec_key_set.Contains(prlimits.SecurityLimits[i].SecurityKey)) + prlimits.SecurityLimits.RemoveAt(i); + } + return prlimits; + } + } + public void Dispose() => Disposable.dispose(ref _dispose); + + async Task<(bool success, string error_msg)> _modify_risk_limits(string op_desc, uint account_key, Func modify) { + var api_limits = new ProprietaryRiskLimits(); + var snapshot = await _get_current_admin_data_async(); + if (!snapshot.HasValue) + return (false, "Timed out waiting for data from server."); + var mutable_snap = snapshot.Value.CloneToMutable(); + if (!snapshot.Value.Accounts.TryGetFirst(acc => acc.Id == account_key, out var target_acci)) { + return (false, $"Account id '{account_key}' not found."); + } + var prlimits = target_acci.HasProprietaryRiskLimits ? target_acci.ProprietaryRiskLimits.CloneToMutable() : new ProprietaryRiskLimits(); + prlimits = modify(prlimits); + if (prlimits is null) { + return (false, "Client-side modification function returned null."); + } + var req = new ProprietaryRiskLimitsAPIArgument { + AccountId = account_key, + ProprietaryRiskLimits = prlimits + }; + var reply = await _error_reporter.safe_execute( + () => _service.update_proprietary_risk_limits_async(req), + r => r.IsSuccess, + r => r.ErrorText, + op_desc); + return (reply.success, reply.value.ErrorText); + } + + async Task _get_current_admin_data_async() => + await _service.subscribei_admin_data() + .Where(upd => upd.all.Any()) + .Select(upd => (AdminDataImmutable?)upd.all.First()) + .FirstOrDefaultAsync(TimeSpan.FromSeconds(5)); + //async Task } -} \ No newline at end of file +} diff --git a/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs index dc1d81212..8a2f3b4fb 100644 --- a/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs @@ -252,6 +252,17 @@ namespace System.Collections.Generic { return false; } + public static bool TryGetFirstIndex(this IEnumerable source, Func predicate, out int index) { + if (source == null) throw new ArgumentNullException(nameof(source)); + index = 0; + foreach (T element in source) { + if (predicate(element)) + return true; + index++; + } + return false; + } + public static bool TryGetSingle(this IEnumerable source, out T result) { if (source == null) throw new ArgumentNullException(nameof(source)); using (var en = source.GetEnumerator()) { @@ -716,4 +727,4 @@ namespace System.Collections.Generic { IEnumerator IEnumerable.GetEnumerator() => _list.GetEnumerator(); } } -} \ No newline at end of file +} diff --git a/src/client/spark_core/utils/ObservableExtensions.cs b/src/client/spark_core/utils/ObservableExtensions.cs index a184c02a4..950153a3d 100644 --- a/src/client/spark_core/utils/ObservableExtensions.cs +++ b/src/client/spark_core/utils/ObservableExtensions.cs @@ -1,230 +1,238 @@ -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 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 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.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); - } - } - - // 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); - } -} \ No newline at end of file +using mbts; +using System.Reactive.Subjects; +using System.Reactive.Threading.Tasks; +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(); + + public static Task FirstOrDefaultAsync(this IObservable source, TimeSpan timeout, T default_value = default) { + var cts = new CancellationTokenSource(timeout); + var main_task = source.FirstOrDefaultAsync().ToTask(cts.Token); + var result_task = main_task.ContinueWith(t => t.Status == TaskStatus.RanToCompletion ? t.Result : default_value); + return result_task; + } + + /// + /// 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 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.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); + } + } + + // 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); + } +}