Select Many in Rx [closed]

可紊 提交于 2020-01-11 19:59:27

问题


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.


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/10071187/select-many-in-rx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!