Skip to content

Instantly share code, notes, and snippets.

@amirshim
Created May 17, 2013 21:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amirshim/5602077 to your computer and use it in GitHub Desktop.
Save amirshim/5602077 to your computer and use it in GitHub Desktop.
Future's flatmap holds on to too much in it's closure... here's a simple fixed. Based on code from: https://github.com/scala/scala/blob/1f4a52b4ed9457863e00fe16d18705b6c6cd5db9/src/library/scala/concurrent/Future.scala#L271
def flatMap[S](f: T => Future[S])(implicit executor: ExecutionContext): Future[S] = {
val p = Promise[S]()
onComplete {
case f: Failure[_] => p complete f.asInstanceOf[Failure[S]]
case Success(v) => {
val tempP = p
try {
f(v).onComplete({
case f: Failure[_] => tempP complete f.asInstanceOf[Failure[S]]
case Success(v) => tempP success v
})(internalExecutor)
} catch {
case NonFatal(t) => tempP failure t
}
}
}(executor)
p.future
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment