有没有办法将Seq [Future [X]]变成Enumerator[X]?用例是我想通过抓取网络来获取资源。这将返回一个期货序列,我想返回一个枚举器,它将按照它们首次完成的顺序推送到Iteratee。
看起来Victor Klang的Future select gist可以用来做到这一点 - 虽然看起来效率很低。
注意:有问题的Iteratees和Enumerator是play框架版本2.x给出的,即使用以下导入:import play.api.libs.iteratee._
答案 0 :(得分:3)
使用Victor Klang's select method:
/**
* "Select" off the first future to be satisfied. Return this as a
* result, with the remainder of the Futures as a sequence.
*
* @param fs a scala.collection.Seq
*/
def select[A](fs: Seq[Future[A]])(implicit ec: ExecutionContext):
Future[(Try[A], Seq[Future[A]])] = {
@scala.annotation.tailrec
def stripe(p: Promise[(Try[A], Seq[Future[A]])],
heads: Seq[Future[A]],
elem: Future[A],
tail: Seq[Future[A]]): Future[(Try[A], Seq[Future[A]])] = {
elem onComplete { res => if (!p.isCompleted) p.trySuccess((res, heads ++ tail)) }
if (tail.isEmpty) p.future
else stripe(p, heads :+ elem, tail.head, tail.tail)
}
if (fs.isEmpty) Future.failed(new IllegalArgumentException("empty future list!"))
else stripe(Promise(), fs.genericBuilder[Future[A]].result, fs.head, fs.tail)
}
}
然后我可以得到我需要的东西
Enumerator.unfoldM(initialSeqOfFutureAs){ seqOfFutureAs =>
if (seqOfFutureAs.isEmpty) {
Future(None)
} else {
FutureUtil.select(seqOfFutureAs).map {
case (t, seqFuture) => t.toOption.map {
a => (seqFuture, a)
}
}
}
}
答案 1 :(得分:2)
更好,更短,我觉得更有效的答案是:
def toEnumerator(seqFutureX: Seq[Future[X]]) = new Enumerator[X] {
def apply[A](i: Iteratee[X, A]): Future[Iteratee[X, A]] = {
Future.sequence(seqFutureX).flatMap { seqX: Seq[X] =>
seqX.foldLeft(Future.successful(i)) {
case (i, x) => i.flatMap(_.feed(Input.El(x)))
}
}
}
}
答案 2 :(得分:1)
我确实意识到这个问题已经有点陈旧了,但根据Santhosh的回答和内置的Enumterator.enumerate()实现,我想出了以下内容:
def enumerateM[E](traversable: TraversableOnce[Future[E]])(implicit ec: ExecutionContext): Enumerator[E] = {
val it = traversable.toIterator
Enumerator.generateM {
if (it.hasNext) {
val next: Future[E] = it.next()
next map {
e => Some(e)
}
} else {
Future.successful[Option[E]] {
None
}
}
}
}
请注意,与第一个基于Viktor-select的解决方案不同,此解决方案保留了订单,但您仍可以异步启动所有计算。因此,例如,您可以执行以下操作:
// For lack of a better name
def mapEachM[E, NE](eventuallyList: Future[List[E]])(f: E => Future[NE])(implicit ec: ExecutionContext): Enumerator[NE] =
Enumerator.flatten(
eventuallyList map { list =>
enumerateM(list map f)
}
)
当我偶然发现这个帖子时,后一种方法实际上就是我想要的。希望它可以帮到某人! :)
答案 3 :(得分:0)
您可以使用Java Executor Completeion Service(JavaDoc)构建一个。我们的想法是使用创建一系列新期货,每个期货使用ExecutorCompletionService.take()
等待下一个结果。每个未来都会在前一个未来产生结果时开始。
但是请注意,这可能效率不高,因为在幕后发生了很多同步。使用一些并行映射reduce进行计算可能更有效(例如使用Scala的ParSeq)并让Enumerator等待完整的结果。
答案 4 :(得分:0)
警告:在回答之前未编译
这样的事情:
def toEnumerator(seqFutureX: Seq[Future[X]]) = new Enumerator[X] {
def apply[A](i: Iteratee[X, A]): Future[Iteratee[X, A]] =
Future.fold(seqFutureX)(i){ case (i, x) => i.flatMap(_.feed(Input.El(x)))) }
}
答案 5 :(得分:0)
这是我发现的方便的东西,
def unfold[A,B](xs:Seq[A])(proc:A => Future[B])(implicit errorHandler:Throwable => B):Enumerator[B] = {
Enumerator.unfoldM (xs) { xs =>
if (xs.isEmpty) Future(None)
else proc(xs.head) map (b => Some(xs.tail,b)) recover {
case e => Some((xs.tail,errorHandler(e)))
}
}
}
def unfold[A,B](fxs:Future[Seq[A]])(proc:A => Future[B]) (implicit errorHandler1:Throwable => Seq[A], errorHandler:Throwable => B) :Enumerator[B] = {
(unfold(Seq(fxs))(fxs => fxs)(errorHandler1)).flatMap(unfold(_)(proc)(errorHandler))
}
def unfoldFutures[A,B](xsfxs:Seq[Future[Seq[A]]])(proc:A => Future[B]) (implicit errorHandler1:Throwable => Seq[A], errorHandler:Throwable => B) :Enumerator[B] = {
xsfxs.map(unfold(_)(proc)).reduceLeft((a,b) => a.andThen(b))
}
答案 6 :(得分:0)
我想建议使用广播
def seqToEnumerator[A](futuresA: Seq[Future[A]])(defaultValue: A, errorHandler: Throwable => A): Enumerator[A] ={
val (enumerator, channel) = Concurrent.broadcast[A]
futuresA.foreach(f => f.onComplete({
case Success(Some(a: A)) => channel.push(a)
case Success(None) => channel.push(defaultValue)
case Failure(exception) => channel.push(errorHandler(exception))
}))
enumerator
}
我添加了errorHandling和defaultValues但你可以通过使用onSuccess或onFailure而不是onComplete来跳过它们