Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactive Extensions SelectMany and Concat

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

like image 371
Blair Davidson Avatar asked Oct 10 '14 13:10

Blair Davidson


1 Answers

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.

like image 117
Dave Sexton Avatar answered Nov 12 '22 20:11

Dave Sexton