Skip to content

Instantly share code, notes, and snippets.

@ryandavidhartman
Created August 17, 2015 01:40
Show Gist options
  • Save ryandavidhartman/d885b9431612ccec3684 to your computer and use it in GitHub Desktop.
Save ryandavidhartman/d885b9431612ccec3684 to your computer and use it in GitHub Desktop.
Scala Future flatmap
trait Future[+T] extends Awaitable[T] {
def flatMap[S](f: T => Future[S])(implicit executor: ExecutionContext): Future[S] = {
import impl.Promise.DefaultPromise
val p = new DefaultPromise[S]()
onComplete {
case f: Failure[_] => p complete f.asInstanceOf[Failure[S]]
case Success(v) => try f(v) match {
// If possible, link DefaultPromises to avoid space leaks
case dp: DefaultPromise[_] => dp.asInstanceOf[DefaultPromise[S]].linkRootOf(p)
case fut => fut.onComplete(p.complete)(internalExecutor)
} catch { case NonFatal(t) => p failure t }
}
p.future
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment