Skip to content

Instantly share code, notes, and snippets.

@ryandavidhartman
Created August 17, 2015 01:42
Show Gist options
  • Save ryandavidhartman/f006f3b6433b5752f3af to your computer and use it in GitHub Desktop.
Save ryandavidhartman/f006f3b6433b5752f3af to your computer and use it in GitHub Desktop.
Simplified Future Flatmap
trait Future[+T] {
def flatMap[S](f: T => Future[S])
(implicit executor: ExecutionContext): Future[S] = {
val promise = new Promise[S]()
this.onComplete {
// The first Future (this) failed
case Failure(t) => promise.failure(t)
case Success(v1) =>
// Apply the flatMap function (f) to the first Future's result
Try(f(v1)) match {
// The flatMap function (f) threw an exception
case Failure(t) => promise.failure(t)
case Success(future2) =>
future2.onComplete {
// The second Future failed
case Failure(t) => promise.failure(t)
// Both futures succeeded - Complete the promise
// successfully with the second Future's result.
case Success(v2) => promise.success(v2)
}
}
}
promise.future
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment