Does anyone know of an appropriate replacement for this handmade if/then/else operator for reactive extensions (.Net / C#)?
public static IObservable<TResult> If<TSource, TResult>(
this IObservable<TSource> source,
Func<TSource, bool> predicate,
Func<TSource, IObservable<TResult>> thenSource,
Func<TSource, IObservable<TResult>> elseSource)
{
return source
.SelectMany(
value => predicate(value)
? thenSource(value)
: elseSource(value));
}
Usage example (assuming numbers
is of type IObservable<int>
:
numbers.If(
predicate: i => i % 2 == 0,
thenSource: i => Observable
.Return(i)
.Do(_ => { /* some side effects */ })
.Delay(TimeSpan.FromSeconds(1)), // some other operations
elseSource: i => Observable
.Return(i)
.Do(_ => { /* some other side effects */ }));
Yes there is one: https://github.com/Reactive-Extensions/Rx.NET/blob/develop/Rx.NET/Source/src/System.Reactive/Linq/Observable/If.cs
But why don't use your selfmade version? It seems to work quite well for me.
Sadly there is, as far as I know, no build in operator for this task in .Net.
There is an If
operator in Rx, with these signatures:
// If the specified condition evaluates true, select the thenSource sequence.
// Otherwise, return an empty sequence.
public static IObservable<TResult> If<TResult>(Func<bool> condition,
IObservable<TResult> thenSource);
// If the specified condition evaluates true, select the thenSource sequence.
// Otherwise, return an empty sequence generated on the specified scheduler.
public static IObservable<TResult> If<TResult>(Func<bool> condition,
IObservable<TResult> thenSource, IScheduler scheduler);
// If the specified condition evaluates true, select the thenSource sequence.
// Otherwise, select the elseSource sequence.
public static IObservable<TResult> If<TResult>(Func<bool> condition,
IObservable<TResult> thenSource, IObservable<TResult> elseSource);
It is not an extension method for IObservable<T>
s.
Your handmade If
operator looks more like a variant of the SelectMany
operator to me. I would have named it SelectMany
, since projecting and merging is its primary function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With