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
==========

No comments:

Post a Comment