Files
spark/src/client/spark/Reactive/ReactiveExtensions.cs
T

73 lines
2.5 KiB
C#

#nullable enable
namespace System.Reactive.Linq {
using Spark.Core.Disposables;
using Spark.Reactive;
using System.Windows.Threading;
static class SparkObservableExtensions {
public static IObservable<T> OnDispatcher<T>(
this IObservable<T> source,
DispatcherPriority priority = DispatcherPriority.Background) =>
source.OnDispatcher(Dispatcher.CurrentDispatcher, priority);
public static IObservable<T> OnDispatcher<T>(
this IObservable<T> source,
Dispatcher dispatcher,
DispatcherPriority priority = DispatcherPriority.Background) {
if (dispatcher is null) {
throw new ArgumentNullException(nameof(dispatcher));
}
if (source is DispatcherObservable<T> d) {
/// Use underlying source to avoid redundant <see cref="Dispatcher.InvokeAsync"/> calls
/// on updates (<see cref="DispatcherObservable{T}.Subscribe(IObserver{T})"/>)
source = d.source;
}
return new DispatcherObservable<T>(source, dispatcher, priority);
}
public static IObservable<T> SubscribeOnDispatcher<T>(
this IObservable<T> source,
DispatcherPriority priority = DispatcherPriority.Background) =>
source.SubscribeOnDispatcher(Dispatcher.CurrentDispatcher, priority);
public static IObservable<T> SubscribeOnDispatcher<T>(
this IObservable<T> source,
Dispatcher dispatcher,
DispatcherPriority priority = DispatcherPriority.Background) {
if (dispatcher is null) {
throw new ArgumentNullException(nameof(dispatcher));
}
return Observable.Create<T>(o => {
var locker = new object();
// init sub to a non-null instance, and let 'sub == null' signal
// that the subscription has been disposed
var sub = Disposable.empty;
dispatcher.InvokeAsync(subscribe, priority);
return Disposable.Create(dispose);
void subscribe() {
lock (locker) {
if (sub != null) {
sub = source.Subscribe(o);
}
}
}
void dispose() {
lock (locker) {
Disposable.dispose(ref sub);
}
}
});
}
public static IObservable<TResult> SelectInline<T, TResult>(
this IObservable<T> source, Func<T, TResult> selector) =>
Observable.Create<TResult>(o => source.Subscribe(v => o.OnNext(selector(v))));
}
}