[英]How to globally order multiple ordered observables in Monix
Doesn't use Monix, but I'm not sure if that's relevant不使用 Monix,但我不确定这是否相关
import scala.collection.BufferedIterator
def merge[A:Ordering](xs: Seq[Iterator[A]]) =
new Iterator[A] {
val its = xs.map(_.buffered)
def hasNext = its.exists(_.hasNext)
def next = its.filter{ _.hasNext}
.minBy(_.head)
.next
}
val ys = merge(Seq(List(1,3,5).toIterator, List(2,4,6).toIterator, List(10,11).toIterator))
ys.toList //> res0: List[Int] = List(1, 2, 3, 4, 5, 6, 10, 11)
Since observable is a stream of items, it can be generalized as two types:由于 observable 是一个项目流,它可以概括为两种类型:
Note that, in order to sort correctly, you'll need all the items.请注意,为了正确排序,您需要所有项目。 So, there's no easy way to do this.因此,没有简单的方法可以做到这一点。
For finite streams , you'll have to accumulate all the items and then sort.对于有限流,您必须累积所有项目,然后进行排序。 You can turn this back into an observable with Observable.fromIterable
.您可以使用Observable.fromIterable
将其转回可Observable.fromIterable
。
val items = List((1,3,4), (2,4,5))
val sortedList = Observable
.fromIterable(items)
.flatMap(item => Observable.fromIterable(List(item._1, item._2, item._3)))
.toListL // Flatten to an Observable[Int]
.map(_.sorted)
For infinite streams, the only thing you can do is to buffer the items up to a certain time or size.对于无限流,您唯一可以做的就是将项目缓冲到特定时间或大小。 I don't see any way around since you don't know when the stream will end.我看不到任何方法,因为您不知道流何时结束。
For example,例如,
val itemsStream: Observable[(Int, Int, Int)] = ???
itemsStream
.bufferIntrospective(10)
.flatMap((itemList: List[(Int, Int, Int)]) => // You'll have to sort this
???
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.