Created
August 17, 2015 01:40
-
-
Save ryandavidhartman/d885b9431612ccec3684 to your computer and use it in GitHub Desktop.
Scala 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] 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