Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Many in Rx [closed]

Please any one let me know how the SelectMany 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.

like image 655
StezPet Avatar asked Apr 09 '12 09:04

StezPet


2 Answers

SelectMany is just:

source.Select(selector).Merge();

In other words, it selects the source input into a stream of Observables, then flattens each Observable into a stream of results.

like image 108
Ana Betts Avatar answered Nov 19 '22 16:11

Ana Betts


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" };

files.ToObservable()
                 .SelectMany(file => DownloadFile(file))
                 .Take(3)
                 .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.

like image 23
Asti Avatar answered Nov 19 '22 15:11

Asti