简体   繁体   English

如何在 Monix 中全局订购多个有序的 observable

[英]How to globally order multiple ordered observables in Monix

Suppose I have multiple iterators that are ordered.假设我有多个有序的迭代器。 If I wanted to merge these iterators while globally ordering them (eg [(1,3,4), (2,4,5)] -> [1,2,3,4,4,5] ) using monix how would I do it?如果我想合并这些迭代器,同时使用monix对它们进行全局排序(例如[(1,3,4), (2,4,5)] -> [1,2,3,4,4,5] )我做吗?

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 是一个项目流,它可以概括为两种类型:

  • Finite streams有限流
  • Infinite streams无限流

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.

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