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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With