Created
August 14, 2012 19:25
-
-
Save kevinwright/3351976 to your computer and use it in GitHub Desktop.
producing a collection of futures. One step at a time...
This file contains hidden or 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
| import akka.dispatch.{ExecutionContext, Future, Promise} | |
| import collection.generic.CanBuildFrom | |
| def linearise[T, U, C[T] <: Traversable[T]](s: C[T])(f: T => Future[U])(implicit cbf: CanBuildFrom[C[T], Future[U], C[Future[U]]], e: ExecutionContext): C[Future[U]] = { | |
| val builder = cbf(s) | |
| var prevPromise: Promise[_] = Promise[Unit] success () | |
| def next(i: Iterator[T]): C[Future[U]] = { | |
| if(!i.hasNext) builder.result | |
| else { | |
| val h = i.next() | |
| val promise = Promise[U]() | |
| builder += promise.future | |
| prevPromise onComplete { | |
| _ => promise completeWith f(h) | |
| } | |
| prevPromise = promise | |
| next(i) | |
| } | |
| } | |
| next(s.toIterator) | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No var no cry:
def linearize[T, U, C[T] <: Traversable[T]](s: C[T])(f: T => Future[U])(implicit cbf: CanBuildFrom[C[T], Future[U], C[Future[U]]], e: ExecutionContext): C[Future[U]] = {
def next(prev: Future[_], i: Iterator[T], b: Builder[Future[U], C[Future[U]]]): C[Future[U]] =
if(i.hasNext) {
val h = i.next()
val p = PromiseU
b += p.future
prev onComplete { _ => p completeWith f(h) }
next(p.future, i, b)
} else b.result
next(Future.successful(()), s.toIterator, cbf(s))
}