Created
August 17, 2015 01:42
-
-
Save ryandavidhartman/f006f3b6433b5752f3af to your computer and use it in GitHub Desktop.
Simplified Future Flatmap
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
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