StezPet StezPet - 2 months ago 51
C# Question

Select Many in Rx

Please any one let me know how the

operator in Rx works. I don't know more about this operator in Linq either.

Please explain this with the help of a simple example, and also in what occasion we will use this operator in Rx.


SelectMany combines projection and flattening into a single step. Suppose you have a number of lists like { {1, 2}, {3, 4, 5}, { 6, 7 } } you can use SelectMany to flatten it into a single list like: { 1, 2, 3, 4, 5, 6, 7}

SelectMany in Rx can flatten multiple sequences into one observable (there are actually several overloads).

For a practical example, suppose you have a function DownloadFile(filename) which gives you an Observable which produces a value when the file completes downloading. You can now write:

string[] files = { "http://.../1", "http://.../2", "http://.../3" };

                 .SelectMany(file => DownloadFile(file))
                 .Subscribe(c => Console.WriteLine("Got " + c) , ()=>  Console.WriteLine("Completed!"));

All 3 observables of DownloadFile are flattened into one, so you can wait for 3 values to arrive to see that all downloads are completed.