Tuesday, December 20, 2011

Creating basic observable collections with RX

In the previous article we created some observables which produced only single notification. This time we will focus on more collection like notifications. We will start with the Repeat method which repeats the first argument n-times based on the second argument:
    var source = Observable.Repeat(1, 3);
    
    IDisposable d = source.Subscribe(
                        value => value.Dump(),
                        error => error.Message.Dump(),
                        () => "Completed".Dump()
    );
The above mentioned code snippet uses an extension method defined in the System.ObservableExtensions static class. It provides you several overloaded versions of ObservableExtensions.Subscribe in case you don't want to create your own observer, but only provide the action methods.
If you are using Visual Studio you have to use the subscribe method with System.Console instead of the Dump method.
    IDisposable d = source.Subscribe(
                    Console.WriteLine,
                    error => Console.WriteLine(error),
                    () => Console.WriteLine("Completed")
    );
The output from LINQPad is as follows:
================
1
1
1
Completed
================
Now we are going to create a Range of notifications. The first argument is the starting value and the second is how many values we will receive together:
    var source = Observable.Range(1, 3);
    
    IDisposable d = source.Subscribe(observer);
================
1
2
3
Completed
================
The last example is the most generic one. The Generate extension method needs these five arguments: an initial state, a condition when to stop, an iterator how to get the next value and a result selector to shape the result:
    var source = Observable.Generate(
                    1, 
                    value => value <= 3,
                    value => value + 1,
                    value => value
                    );                    
    
    IDisposable d = source.Subscribe(observer);
The initial state is set to 1. In every "iteration" the state is incremented by one while the condition is met. The resulting shape of the values won't be changed in this case. This time we have created the exactly same functionality as the Repeat method provides:
================
1
2
3
Completed
================
Next time we will create a testable observable.

No comments:

Post a Comment