Reactive Extensions SelectMany and Concat

ぐ巨炮叔叔 提交于 2019-12-10 17:51:44

问题


I understand that the behaviour of SelectMany is to effectively merge the results of each value produced into a single stream so the ordering in nondeterministic.

How do I do something similar to concatAll in RxJs in C#.

var obs = Observable.Range (1, 10).SelectMany (x => {
return Observable.Interval (TimeSpan.FromSeconds(10 - x)).Take (3);
}).Concat();

This is effectively what I want to do, Given a Range, Wait a bit for each then concat in the order that they started in. Obviously this is a toy example but the idea is there.

Blair


回答1:


Use Select, not SelectMany. The Concat overload that you want to use works on an IObservable<IObservable<T>>, so simply project the inner sequences, don't flatten them.

var obs = Observable.Range(1, 10)
                    .Select(x => Observable.Interval(TimeSpan.FromSeconds(10 - x)).Take(3))
                    .Concat();

Note that the subscrition of each Interval is deferred by using Concat; i.e., the first Interval starts right away when you subscribe, but all of the remaining intervals are generated and enqueued without subscription. It's not like Concat will subscribe to everything and then replay the values in the correct order later.



来源:https://stackoverflow.com/questions/26300072/reactive-extensions-selectmany-and-concat

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