Last active
December 17, 2017 02:18
-
-
Save viktorklang/4488970 to your computer and use it in GitHub Desktop.
Scala Concurrent port of https://github.com/twitter/util/blob/master/util-core/src/main/scala/com/twitter/util/Future.scala#L331-336
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* "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]])] = { | |
@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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. I use this code to show how to transform a Seq[Future[X]] into an Enumerator[X]
http://stackoverflow.com/questions/15543261/transforming-a-seqfuturex-into-an-enumeratorx/15545906