9

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.

Pierre Arnaud
  • 10,212
  • 11
  • 77
  • 108
StezPet
  • 2,430
  • 2
  • 27
  • 49

3 Answers3

25

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.

Ana Betts
  • 73,868
  • 16
  • 141
  • 209
23

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.

Asti
  • 12,447
  • 29
  • 38
10

I found this short video helpful in understanding SelectMany for Rx (and as a more advanced use of marble diagrams): http://channel9.msdn.com/Blogs/J.Van.Gogh/Reactive-Extensions-API-in-depth-SelectMany

yamen
  • 15,390
  • 3
  • 42
  • 52