public static IObservable <T> XMax <T>(this IObservable <T> sequence) where T : IComparable <T> { IObservable <T> result = sequence.Aggregate( (max, currentVal) => currentVal.CompareTo(max) == 1 ? currentVal : max); return(result); }
public static IObservable <double> Average(this IObservable <double> source, double seed) { return(Observable.Create <double>( o => { double count = 1; double total = 0; return source .Aggregate(seed, (acc, currentValue) => { count++; return acc + currentValue; }) .Take(1) .Subscribe( acc => total = acc, e => o.OnError(e), () => { //Debug.LogFormat("total {0} count {1}", total, count); if (0 < count) { o.OnNext(total / count); } o.OnCompleted(); }); })); }
public void TestSharedSourceStream() { IHystrixCommandKey key = HystrixCommandKeyDefault.AsKey("CMD-Health-N"); stream = HealthCountsStream.GetInstance(key, 10, 100); CountdownEvent latch = new CountdownEvent(1); AtomicBoolean allEqual = new AtomicBoolean(false); IObservable <HealthCounts> o1 = stream .Observe() .Take(10) .ObserveOn(TaskPoolScheduler.Default); IObservable <HealthCounts> o2 = stream .Observe() .Take(10) .ObserveOn(TaskPoolScheduler.Default); IObservable <bool> zipped = Observable.Zip(o1, o2, (healthCounts, healthCounts2) => { return(healthCounts == healthCounts2); // we want object equality }); IObservable <bool> reduced = zipped.Aggregate(true, (a, b) => { return(a && b); }).Select(n => n); var rdisp = reduced.Subscribe( (b) => { output.WriteLine(Time.CurrentTimeMillis + " : " + Thread.CurrentThread.ManagedThreadId + " Reduced OnNext : " + b); allEqual.Value = b; }, (e) => { output.WriteLine(Time.CurrentTimeMillis + " : " + Thread.CurrentThread.ManagedThreadId + " Reduced OnError : " + e); output.WriteLine(e.ToString()); latch.SignalEx(); }, () => { output.WriteLine(Time.CurrentTimeMillis + " : " + Thread.CurrentThread.ManagedThreadId + " Reduced OnCompleted"); latch.SignalEx(); }); for (int i = 0; i < 10; i++) { HystrixCommand <int> cmd = Command.From(groupKey, key, HystrixEventType.SUCCESS, 20); cmd.Execute(); } Assert.True(latch.Wait(10000), "CountdownEvent was not set!"); Assert.True(allEqual.Value); rdisp.Dispose(); // we should be getting the same object from both streams. this ensures that multiple subscribers don't induce extra work }
/// <summary> /// Aggregate observable into list /// </summary> public static IObservable <IList <T> > CollectToList <T>(this IObservable <T> observable) { return(observable.Aggregate(new List <T>(), (list, item) => { list.Add(item); return list; })); }
/// <summary> /// <para>Calculates the minimum of the items emitted by the observable. Derived from Aggregate.</para> /// /// <para>Set of similar extensions: Count Sum Min Max</para> /// /// <see cref="http://www.introtorx.com/Content/v1.0.10621.0/07_Aggregation.html#Aggregate"/> public static IObservable <T> Min <T>(this IObservable <T> source) { Func <T, T, int> compare = Comparer <T> .Default.Compare; return(source.Aggregate( (min, current) => compare(min, current) > 0 ? current : min )); }
public static IObservable <List <T> > ToConcreteList <T>(this IObservable <T> source) { return(source.Aggregate(new List <T>(), (list, item) => { list.Add(item); return list; })); }
public static void SumWithAggregate() { IObservable <Trade> trades = Trade.TestStream(); IObservable <long> tradeVolume = trades.Aggregate( 0L, (total, trade) => total + trade.Number); tradeVolume.Subscribe(Console.WriteLine); }
public static IObservable <T> Min <T>(this IObservable <T> source, T seed) { return(source.Aggregate(seed, (min, current) => Comparer <T> .Default .Compare(min, current) > 0 ? current : min)); }
/// <summary> /// Aggregate only publish out its final result, median result won't be published out /// </summary> private static void TestAggregate() { IObservable <long> source = Observable.Interval(TimeSpan.FromMilliseconds(150)).Take(10); IObservable <long> aggregated = source.Aggregate((sum, current) => sum + current); var endEvent = new ManualResetEventSlim(false); aggregated.Subscribe(num => Console.WriteLine("sum={0}", num), endEvent.Set); endEvent.WaitHandle.WaitOne(); }
private ChannelReader <T> AsSignalRChannel <T>(IObservable <T> observable, CancellationToken cancellationToken) { var channel = Channel.CreateUnbounded <T>(); observable .Aggregate(Task.CompletedTask, (prevTask, next) => prevTask.ContinueWith(t => channel.Writer.WriteAsync(next).AsTask().ContinueWith(_ => logger.LogInformation("Sent state."))).Unwrap()) .Select(next => Observable.FromAsync(() => next)) .Concat() .Subscribe(_ => { }, ex => channel.Writer.Complete(ex), () => channel.Writer.Complete(), cancellationToken); return(channel.Reader); }
/// <summary> /// <para>Calculates the maximum of the items emitted by the observable. Derived from Aggregate.</para> /// /// <para>Set of similar extensions: Count Sum Min Max</para> /// /// <see cref="http://www.introtorx.com/Content/v1.0.10621.0/07_Aggregation.html#Aggregate"/> public static IObservable <T> Max <T>(this IObservable <T> source) { var comparer = Comparer <T> .Default; return(source.Aggregate((x, y) => { if (comparer.Compare(x, y) < 0) { return y; } return x; })); }
public static IObservable <T> Max <T>(this IObservable <T> source, T seed) { var comparer = Comparer <T> .Default; Func <T, T, T> max = (x, y) => { if (comparer.Compare(x, y) < 0) { return(y); } return(x); }; return(source.Aggregate(seed, max)); }
public Task <IList <T> > AsFuture <T>(IObservable <T> observable, CancellationToken?token) { var obsEnumerable = observable.Aggregate((IList <T>) new List <T>(), (acc, v) => { acc.Add(v); return(acc); }); Task <IList <T> > task = token.HasValue ? obsEnumerable.ToTask(token.Value) : obsEnumerable.ToTask(); return(task); }
/// <summary> /// Aggregates all the Ticks and creates OHLC bar /// </summary> /// <param name="source"></param> /// <returns></returns> public static IObservable <OHLC> OHLC(this IObservable <Tick> source) { return(source.Aggregate((OHLC)null, (oh, tk) => { // update or create (upsert) OHLC if (oh != null) { oh.Add(tk); } else { oh = new OHLC(tk); } return oh; })); }
public static IObservable <T> Max <T>(this IObservable <T> source) { // "Comparer<T>.Default" // : It simply returns an instance of the internal class GenericComparer<T> something like that. /* * internal class GenericComparer<T> : Comparer<T> where T : IComparable<T> * { * public override int Compare(T x, T y) * { * if (x != null) * { * if (y != null) * return x.CompareTo(y); * return 1; * } * else * { * if (y != null) * return -1; * return 0; * } * } * * // ... * } */ // This class has the constraint that T must implement IComparable<T> // so it can simply delegate the calls to it Compare method to the Compare methods of the instances it gets passed. var comparer = Comparer <T> .Default; Func <T, T, T> max = (x, y) => { if (comparer.Compare(x, y) < 0) { return(y); } return(x); }; return(source.Aggregate(max)); }
public static IObservable <String> ToString(this IObservable <object> source, String separator) { if (source == null) { throw new ArgumentException("Parameter source can not be null."); } if (String.IsNullOrEmpty(separator)) { throw new ArgumentException("Parameter separator can not be null or empty."); } return(source .Aggregate ( String.Empty, (o1, o2) => String.Concat(o1, String.IsNullOrWhiteSpace(o1) ? String.Empty : separator, o2) ) .Where(s => !String.IsNullOrWhiteSpace(s)) ); }
public ReactiveDerivedCollectionFromObservable( IObservable <T> observable, TimeSpan?withDelay = null, Action <Exception> onError = null, IScheduler scheduler = null) { scheduler = scheduler ?? RxApp.MainThreadScheduler; _inner = new SingleAssignmentDisposable(); onError = onError ?? (ex => RxApp.DefaultExceptionHandler.OnNext(ex)); if (withDelay == null) { _inner.Disposable = observable.ObserveOn(scheduler).Subscribe(InternalAdd, onError); return; } // On a timer, dequeue items from queue if they are available var queue = new Queue <T>(); var disconnect = Observable.Timer(withDelay.Value, withDelay.Value, scheduler) .Subscribe(_ => { if (queue.Count > 0) { InternalAdd(queue.Dequeue()); } }); _inner.Disposable = disconnect; // When new items come in from the observable, stuff them in the queue. observable.ObserveOn(scheduler).Subscribe(queue.Enqueue, onError); // This is a bit clever - keep a running count of the items actually // added and compare them to the final count of items provided by the // Observable. Combine the two values, and when they're equal, // disconnect the timer ItemsAdded.Scan(0, (acc, _) => acc + 1).Zip( observable.Aggregate(0, (acc, _) => acc + 1), (l, r) => l == r).Where(x => x).Subscribe(_ => disconnect.Dispose()); }
/// <summary> /// Creates a collection based on an an Observable by adding items /// provided until the Observable completes, optionally ensuring a /// delay. Note that if the Observable never completes and withDelay is /// set, this method will leak a Timer. This method also guarantees that /// items are always added via the UI thread. /// </summary> /// <param name="fromObservable">The Observable whose items will be put /// into the new collection.</param> /// <param name="onError">The handler for errors from the Observable. If /// not specified, an error will go to DefaultExceptionHandler.</param> /// <param name="withDelay">If set, items will be populated in the /// collection no faster than the delay provided.</param> /// <returns>A new collection which will be populated with the /// Observable.</returns> public static ReactiveCollection <T> CreateCollection <T>( this IObservable <T> fromObservable, TimeSpan?withDelay = null, Action <Exception> onError = null) { var ret = new ReactiveCollection <T>(); onError = onError ?? (ex => RxApp.DefaultExceptionHandler.OnNext(ex)); if (withDelay == null) { fromObservable.ObserveOn(RxApp.DeferredScheduler).Subscribe(ret.Add, onError); return(ret); } // On a timer, dequeue items from queue if they are available var queue = new Queue <T>(); var disconnect = Observable.Timer(withDelay.Value, withDelay.Value, RxApp.DeferredScheduler) .Subscribe(_ => { if (queue.Count > 0) { ret.Add(queue.Dequeue()); } }); // When new items come in from the observable, stuff them in the queue. // Using the DeferredScheduler guarantees we'll always access the queue // from the same thread. fromObservable.ObserveOn(RxApp.DeferredScheduler).Subscribe(queue.Enqueue, onError); // This is a bit clever - keep a running count of the items actually // added and compare them to the final count of items provided by the // Observable. Combine the two values, and when they're equal, // disconnect the timer ret.ItemsAdded.Scan(0, ((acc, _) => acc + 1)).Zip(fromObservable.Aggregate(0, (acc, _) => acc + 1), (l, r) => (l == r)).Where(x => x).Subscribe(_ => disconnect.Dispose()); return(ret); }
public static IObservable <double> Sum(this IObservable <double> source, double seed) { return(source.Aggregate(seed, (acc, currentValue) => acc + currentValue)); }
public static IObservable <double> Sum <TSource>(this IObservable <TSource> source, Func <TSource, double> selector) { return(source.Aggregate(0.0, (a, b) => a + selector(b))); }
public static IObservable <double> Sum(this IObservable <double> source) { return(source.Aggregate(0.0, (a, b) => a + b)); }
public static IObservable <Unit> AsCompletion <T>(this IObservable <T> observable) { return(observable.Aggregate(Unit.Default, (unit, _) => unit)); }
public static IObservable <int> MySum(this IObservable <int> source) { return(source.Aggregate(0, (acc, currentValue) => acc + currentValue)); }
public static IObservable <Unit> DeleteAll(this IObservable <IEnumerable <Entity> > source, Func <Entity, IObservable <Unit> > delete) { return(source.Aggregate((acc, curr) => acc.Concat(curr)).SelectMany(tasks => tasks) .SelectMany(delete).LastOrDefaultAsync()); }
public static IObservable <Vector2> Smooth(this IObservable <Vector2> This, Vector2 initialValue, float smoothness) => This.Aggregate(initialValue, (acc, value) => value.Smooth(acc, smoothness));
public static IObservable <int> MyCount(this IObservable <int> source) { return(source.Aggregate(0, (acc, _) => acc + 1)); }
public static IObservable <float> Sum(this IObservable <float> source) { return(source.Aggregate((acc, currentValue) => acc + currentValue)); }