Files
spark/src/client/spark_core/Reactive/ObservableExtensions.cs
T

352 lines
16 KiB
C#

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<bool> And(this IObservable<bool> source1, IObservable<bool> source2) =>
source1.CombineLatest(source2).Select(tup => tup.Item1 && tup.Item2);
/// <summary>
/// <para>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.</para>
/// <para>Whenever the source produces an update, the heartbeat evaluates to true and the heartbeat duration clock is reset.</para>
/// <para>Whenever heartbeat duration clock expires, the heartbeat evaluates to false.</para>
/// </summary>
/// <typeparam name="T">Type of data produced by the source (bears no impact on the resultant observable heartbeat</typeparam>
/// <param name="source">The source that will indicate alive/dead by publishing updates within the duration period</param>
/// <param name="duration">The amount of time that must pass without receiving an update from the source to determine the heartbeat is not detected</param>
/// <returns>An "Observable Heartbeat"</returns>
public static IObservable<bool> AsHeartbeat<T>(this IObservable<T> source, TimeSpan duration) {
IObservable<bool> dead = source.Throttle(duration).Select(_ => false);
IObservable<bool> alive = source.Select(_ => true);
return dead.Merge(alive).DistinctUntilChanged();
}
public static IObservable<T> Bootstrap<T>(this IObservable<T> source, Func<T, T> bootstrap_selector) =>
source.Bootstrap(bootstrap_selector, _ => _);
public static IObservable<TResult> Bootstrap<T, TResult>(
this IObservable<T> source, Func<T, TResult> bootstrap_selector, Func<T, TResult> selector) =>
Observable.Create<TResult>(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<T> BufferLatest<T>(this IObservable<T> 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<T>(
this IObservable<T> 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<T>(
this IObservable<T> source,
Func<T, bool> 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<T, TResult>(
this IObservable<T> source,
Func<T, bool> predicate,
Func<T, TResult> 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<T> FlattenSeries<T>(
this IObservable<IObservable<T>> outer_source, Func<T, T, T> bridge) {
return Observable.Create<T>(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<T> 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();
}
});
}
/// <summary>
/// A less verbose way to call <see cref="Observable.FromEvent{Action{TEventArgs}, TEventArgs}(Action{Action{TEventArgs}}, Action{Action{TEventArgs}})"/>.
/// </summary>
public static IObservable<T> FromAction<T>(Action<T> event_source) =>
Observable.FromEvent<Action<T>, T>(cb => event_source += cb, cb => event_source -= cb);
public static IObservable<T> FromEvent<T>(Action<Action> add_handler, Action<Action> remove_handler, Func<T> selector) =>
Observable.Create<T>(o => {
callback();
add_handler(callback);
return Disposable.Create(() => remove_handler(callback));
void callback() => o.OnNext(selector());
});
public static IObservable<T> FromEventThrottle<T>(Action<Action<T>> add_handler, Action<Action<T>> remove_handler, TimeSpan throttle) =>
FromEventThrottle<T>(cb => {
add_handler(cb);
return Disposable.Create(() => remove_handler(cb));
}, throttle);
public static IObservable<T> FromEventThrottle<T>(Func<Action<T>, IDisposable> add_handler, TimeSpan throttle) =>
Observable.Create<T>(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<TResult> FromEventThrottle<T, TResult>(Action<Action<T>> add_handler, Action<Action<T>> remove_handler, Func<T, TResult> selector, TimeSpan throttle) =>
FromEventThrottle(cb => {
add_handler(cb);
return Disposable.Create(() => remove_handler(cb));
}, selector, throttle);
public static IObservable<TResult> FromEventThrottle<T, TResult>(Func<Action<T>, IDisposable> add_handler, Func<T, TResult> selector, TimeSpan throttle) =>
Observable.Create<TResult>(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<TSource>(this IObservable<TSource> source) =>
PairWithPrevious(source, default);
public static IObservable<(TSource prev, TSource curr)> PairWithPrevious<TSource>(this IObservable<TSource> source, TSource default_value) =>
source.Scan<TSource, (TSource prev, TSource curr)>((default_value, default_value), (last, next) => (last.curr, next));
public static IObservable<T> RefCountReplay<T>(this IObservable<T> 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<T> replay = new ReplaySubject<T>(buffer_size);
IDisposable source_sub = null;
return Observable.Create<T>(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();
});
});
}
/// <summary>
/// Uses each element of a source observable to create an inner observable of <typeparamref name="TResult"/>, unlike <see cref="Observable.SelectMany{TSource, TResult}(IObservable{TSource}, Func{TSource, IObservable{TResult}})"/>,
/// each inner sequence is terminated when the next one begins.
/// <para/>In other words, observers are notified by the inner observerables in &quot;series,&quot; rather than &quot;parallel.&quot;
/// </summary>
/// <typeparam name="TSource">The type of elements in the source (outer) sequence.</typeparam>
/// <typeparam name="TResult">The type of elements in the inner sequences.</typeparam>
/// <param name="source">A sequence of elements to create a series of inner sequences.</param>
/// <param name="select_next">A function to create an inner sequence.</param>
/// <returns>An IDisposable object used to unsubscribe from the source (outer) sequence, and the latest inner sequence.</returns>
public static IObservable<TResult> SelectSeries<TSource, TResult>(this IObservable<TSource> source, Func<TSource, IObservable<TResult>> select_next) =>
Observable.Create<TResult>(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<T> StartWith<T>(this IObservable<T> source, Func<T> get_value) =>
Observable.Create<T>(o => {
o.OnNext(get_value());
return source.Subscribe(o);
});
public static IObservable<T> StartWith<T>(this IObservable<T> source, Func<T> get_value, Func<bool> can_get_value) =>
Observable.Create<T>(o => {
if (can_get_value())
o.OnNext(get_value());
return source.Subscribe(o);
});
public static IDisposable Subscribe<T>(this IObservable<T> source, params IObserver<T>[] 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();
}
}
/// <summary>
/// An inner subscription is made for each value in the source sequence using the specified delegate (<paramref name="subscribe_value"/>).
/// When a new value arrives, the subscription for the previous value is disposed before <paramref name="subscribe_value"/> is invoked with the new value.
/// </summary>
/// <typeparam name="T">The type of elements in the source sequence.</typeparam>
/// <param name="source">A sequence of elements to invoke a subscribe function on.</param>
/// <param name="subscribe_value">A function used to subscribe each source element.</param>
/// <returns>An IDisposable object used to unsubscribe from the source sequence, and dispose the latest value subscription.</returns>
public static IDisposable SubscribeEach<T>(this IObservable<T> source, Func<T, IDisposable> 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<T> ToObservable<T>(
this IConnectableObservable<T> 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<TResult> TrySelect<T, TResult>(this IObservable<T> source, Func<T, (TResult result, bool success)> try_select) =>
source.Select(try_select).Where(ts => ts.success).Select(ts => ts.result);
public static IObservable<T> StopAfter<T>(this IObservable<T> source, TimeSpan duration) {
return Observable.Create<T>(o => {
int state = 0;
IDisposable sub = null;
sub = source.Subscribe(new AnonymousObserver<T>(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<T> WhereValues<T>(this IObservable<T?> source) where T : struct =>
Observable.Create<T>(o =>
source.Subscribe(v => {
if (v.HasValue) {
o.OnNext(v.Value);
}
}));
}
}