简体   繁体   English

为什么这些Rx序列乱序?

[英]Why are these Rx sequences out of order?

Suppose I write 假设我写

var gen = Observable.Range(1, 3)
  .SelectMany(x => Observable.Range(1, x));

The sequence produced is 1 1 2 1 2 3 as expected. 产生的序列如预期的那样是1 1 2 1 2 3 But now if I write 但是如果我写的话

var gen = Observable.Range(1, 4)
  .SelectMany(x => Observable.Range(1, x));

Now the sequence produced is 1 1 2 1 2 1 3 2 3 4 instead of what one would expect 1 1 2 1 2 3 1 2 3 4 . 现在产生的序列是1 1 2 1 2 1 3 2 3 4而不是人们期望的1 1 2 1 2 3 1 2 3 4 Why is that? 这是为什么? Does SelectMany() do some kind of multithreaded merge? SelectMany()是否会进行某种多线程合并?

Observable.Range() itself will always generate its events in order. Observable.Range()本身将始终按顺序生成其事件。 However SelectMany() doesn't wait for the previous observable to complete before starting the next one. 但是,在启动下一个observable之前, SelectMany()不会等待先前的observable完成。 Which means that as the sequences get longer, there will be more and more overlap, since the next sequence will start before the previous has completed and so on. 这意味着随着序列变长,将会有越来越多的重叠,因为下一个序列将在前一个序列完成之前开始,依此类推。

If you are trying to get the output to be sequential, then you will need to use a different means of flattening the sequence, such as Concat() . 如果您试图使输出顺序,那么您将需要使用不同的方法来展平序列,例如Concat()

Eg: 例如:

var gen = Observable.Range(1, 4)
  .Select(x => Observable.Range(1, x)).Concat();

Output: 1,1,2,1,2,3,1,2,3,4 产出:1,1,2,1,2,3,1,2,3,4

Unlike SelectMany() , Concat() does wait for each sequence to complete before starting the next one. SelectMany()不同, Concat() 在开始下一个序列之前等待每个序列完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM