Skip to content

Instantly share code, notes, and snippets.

@kevinwright
Created August 14, 2012 19:25
Show Gist options
  • Select an option

  • Save kevinwright/3351976 to your computer and use it in GitHub Desktop.

Select an option

Save kevinwright/3351976 to your computer and use it in GitHub Desktop.
producing a collection of futures. One step at a time...
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)
}
@viktorklang
Copy link

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))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment