Thursday, January 5, 2012

How to use SelectMany in Reactive Extensions (RX).

You can use the SelectMany extension method in several different ways. The first example shows you that the SelectMany can be used to flatten the result of the Window method from IObservable<IObservable<T>> to IObservable<T>.
var source = Observable.Repeat(1, 3)
            .Window(2)
            .SelectMany(c => c);

source.Subscribe(
    value => value.Dump(),
    error => Console.WriteLine(error.Message),
    () => Console.WriteLine("Completed")
);    
==========
1
1
1
Completed
==========
Or you can produce a collection of values for each produced value:
var source = Observable.Range(1, 3)
            .SelectMany(c => Observable.Repeat(c,3));
==========
1
1
2
1
2
3
2
3
3
Completed
==========
Instead of another observable you can use an enumerable and project the resulting values with result selector:
var source = Observable.Range(1, 3)
            .SelectMany(c => Enumerable.Repeat(c,3), (x, y) => x*y);
==========
1
1
1
4
4
4
9
9
9
Completed
==========
Finally you could produce a new observable for each action - OnNext, OnError and OnCompleted:
var source = Observable.Range(1, 3)
            .SelectMany(value => Observable.Return(1), 
                        error => Observable.Return(-1),
                        () => Observable.Return(0));
==========
1
1
1
0
Completed
==========

Tuesday, January 3, 2012

How to recursively call IScheduler.Schedule in Reactive Extensions.

The following example demonstrates how to recursively call the schedulers Schedule method in order to call itself. The result of this is a "lazy infinite loop":
public static class ObservableExt
{    

    public static IObservable<int> Natural()
    {
        return Natural(Scheduler.CurrentThread);
    }
    
    public static IObservable<int> Natural(IScheduler scheduler)
    {
        if (scheduler == null)
        {
            throw new ArgumentNullException("scheduler");
        }
        int i = 0;
            
        return Observable.Create<int>(observer => {
            return scheduler.Schedule(action => {
                observer.OnNext(i++);
                action();
            });
        });
    }
}
Now we can call the Natural extension method and chain it with other extension methods from RX library. This example uses Take to stop the production of infinite number of values after 5 items.
IObservable<int> naturals = ObservableExt.Natural()
                                         .Take(3);

naturals.Subscribe(
    value => value.Dump(),
    error => Console.WriteLine(error.Message),
    () => Console.WriteLine("Completed")
);    
==========
0
1
2
Completed
==========

Monday, January 2, 2012

The difference between OfType and Cast in Reactive Extensions (RX).

OfType tries to convert an object to the defined type or ignores it if the value is not of the defined type.
public class Person
{
    public string Name { get; set; }
}

object value = new Person { Name = "Kinga" };

var source = Observable.Return(new object())
                       .Concat(Observable.Return(value))
                       .OfType<Person>()
                       .Select(p => p.Name);
==========
OnNext : Kinga
OnCompleted
==========
The Cast method propagates an OnError if the value is not convertable to the defined type and stops the subscription
object value = new Person { Name = "Kinga" };

var source = Observable.Return(new object())
                       .Concat(Observable.Return(value))
                       .Cast<Person>()
                       .Select(p => p.Name);
==========
OnError : Unable to cast object of type 'System.Object' to type 'Person'.
==========

Sunday, January 1, 2012

Combining observable sequences with Concat, Merge, Catch, OnErrorResumeNext and CombineLatest in Reactive Extensions (RX).

Concat concatenates observable sequences in the order you have provided the observables to it:

var source1 = Observable.Repeat(1, 3);

var source2 = Observable.Repeat(2, 3);

source1.Concat(source2)
       .Subscribe(Console.WriteLine);
So it propagates first all values from the source1 and then from the source2 observable sequence:
==========
1
1
1
2
2
2
==========
An error calls the OnError action and ends the subscription:
var source1 = Observable.Repeat(1, 3)
    .Concat(Observable.Throw<int>(new Exception("An error has occurred.")))
    .Concat(Observable.Repeat(1, 3));

var source2 = Observable.Repeat(2, 3);

source1.Concat(source2)
       .Subscribe(Console.WriteLine, error => Console.WriteLine(error.Message));
==========
1
1
1
An error has occurred.
==========
On the other hand the Merge extension method takes periodically a value from each provided observable sequence:
var source1 = Observable.Repeat(1, 3);

var source2 = Observable.Repeat(2, 3);

source1.Merge(source2)
       .Subscribe(Console.WriteLine);
==========
1
2
1
2
1
2
==========
An error again calls the OnError action and ends the subscription:
var source1 = Observable.Repeat(1, 3)
    .Concat(Observable.Throw<int>(new Exception("An error has occurred.")))
    .Concat(Observable.Repeat(1, 3));

var source2 = Observable.Repeat(2, 3);

source1.Merge(source2)
       .Subscribe(Console.WriteLine, error => Console.WriteLine(error.Message));
==========
1
2
1
2
1
An error has occurred.
==========
Catch propagates the first sequence if everything went OK and ignores the second one, otherwise propagates also the values from the second observable and values from the first one up to the time an error occurred.
var source1 = Observable.Repeat(1, 3);

var source2 = Observable.Repeat(2, 3);

source1.Catch(source2)
       .Subscribe(Console.WriteLine);    
==========
1
1
1
==========
var source1 = Observable.Repeat(1, 3)
    .Concat(Observable.Throw<int>(new Exception("An error has occurred.")))
    .Concat(Observable.Repeat(1, 3));

var source2 = Observable.Repeat(2, 3);

source1.Catch(source2)
       .Subscribe(Console.WriteLine, error => Console.WriteLine(error.Message));
OnError is not called in this case:
==========
1
1
1
2
2
2
==========
OnErrorResumeNext produces values from both sequences if an error hasn't occurred like Concat:
var source1 = Observable.Repeat(1, 3);

var source2 = Observable.Repeat(2, 3);

source1.OnErrorResumeNext(source2)
       .Subscribe(Console.WriteLine);    
==========
1
1
1
2
2
2
==========
but in case something went wrong with the first one it will stop producing values from it and concatenates values from the second one to it:
var source1 = Observable.Repeat(1, 3)
    .Concat(Observable.Throw<int>(new Exception("An error has occurred.")))
    .Concat(Observable.Repeat(1, 3));

var source2 = Observable.Repeat(2, 3);

source1.OnErrorResumeNext(source2)
       .Subscribe(Console.WriteLine, error => Console.WriteLine(error.Message));
OnError is not called in this case:
==========
1
1
1
2
2
2
==========
Finally CombineLatest returns an observable sequence containing the result of combining elements of both sources using the specified result selector function.
var semaphore = new SemaphoreSlim(0);

var observer = Observer.Create<string>(
    value => Console.WriteLine(value.ToString()),
    error => { 
        Console.WriteLine(error.Message); 
        semaphore.Release(); 
    },
    () => { 
        Console.WriteLine("Completed"); 
        semaphore.Release(); 
    }
);    

var source1 = Observable.Interval(TimeSpan.FromSeconds(1))
                        .Timestamp()
                        .Take(3);

var source2 = Observable.Interval(TimeSpan.FromSeconds(3))
                        .Timestamp()
                        .Take(3);

var input = source1.CombineLatest(source2, (x, y) => { 
    return string.Format("{0} - {1}", x.ToString(), y.ToString());
});

using(input.Subscribe(observer))
{
    semaphore.Wait();
}
==========
1@27.12.2011 18:26:47 +01:00 - 0@27.12.2011 18:26:48 +01:00
2@27.12.2011 18:26:48 +01:00 - 0@27.12.2011 18:26:48 +01:00
2@27.12.2011 18:26:48 +01:00 - 1@27.12.2011 18:26:51 +01:00
2@27.12.2011 18:26:48 +01:00 - 2@27.12.2011 18:26:54 +01:00
Completed
==========