Created
February 14, 2013 15:37
-
-
Save bmc/4953591 to your computer and use it in GitHub Desktop.
Simulate Play 2.0 Future.await() in Play 2.1 (for backward compatibility)
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
package lib | |
import scala.concurrent.Future | |
import scala.concurrent.duration._ | |
import play.api.libs.concurrent.Execution.Implicits._ | |
object ConcurrentUtil { | |
import scala.language.{implicitConversions, postfixOps} | |
/** Additions to Future. | |
*/ | |
class RichFuture[+T](val future: Future[T]) { | |
class NotWaiting[+A](future: Future[A]) { | |
import scala.concurrent.Await | |
def fold[B](onError: (Throwable) => B, onSuccess: (A) => B): B = { | |
try { | |
onSuccess(Await.result(future, 30 seconds)) | |
} | |
catch { | |
case e: Throwable => onError(e) | |
} | |
} | |
def get: A = Await.result(future, 30 seconds) | |
} | |
/** Simulate Play 2.0 await() for a Future, because this pattern is | |
* sometimes useful. The result should be folded over. e.g.: | |
* | |
* val f = Future { ... } | |
* f.await.fold( | |
* { ex: Throwable => | |
* ... | |
* }, | |
* { result => | |
* ... | |
* } | |
* ) | |
*/ | |
def await: NotWaiting[T] = new NotWaiting(future) | |
} | |
implicit def futureToRichFuture[A](f: Future[A]) = | |
new RichFuture(f) | |
implicit def RichFutureToFuture[A](t: RichFuture[A]) = | |
t.future | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment