Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an if/then/else operator for observables in c# available?

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 */ }));
like image 929
Daniel Müller Avatar asked Apr 11 '17 13:04

Daniel Müller


2 Answers

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.

like image 86
MetaColon Avatar answered Nov 09 '22 11:11

MetaColon


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.

like image 1
Theodor Zoulias Avatar answered Nov 09 '22 11:11

Theodor Zoulias