Last active
December 22, 2015 06:08
-
-
Save Mortimerp9/6428552 to your computer and use it in GitHub Desktop.
Because sometimes you are running an "old" version of Akka with a Scala version providing its own Future (>2.9.3, >2.10), then you need to juggle between one and the other.
There are implicits to convert Akka and Scala Futures one to the other
This file contains 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
import scala.concurrent.duration.{Duration => ScalaDuration} | |
import scala.concurrent.{ExecutionContext => ScalaExecutionContext, Future => ScalaFuture, Promise => ScalaPromise} | |
import scala.util.{Success, Failure} | |
import akka.dispatch.{ExecutionContext => AkkaExecutionContext, Future => AkkaFuture, Promise => AkkaPromise} | |
import akka.util.{Duration => AkkaDuration} | |
/** | |
* Some compatibility implicit conversions to deal with akka as if it might already be a newer version | |
* (using scala interfaces instead of akka). | |
* | |
* User: pierre | |
* Date: 7/8/13 | |
* Time: 10:09 AM | |
*/ | |
object AkkaCompat { | |
/** | |
* convert a scala duration to an akka duration | |
* @param d | |
* @return | |
*/ | |
implicit def durationConversion(d: ScalaDuration): AkkaDuration = AkkaDuration.fromNanos(d.toNanos) | |
implicit def akkaExCtxToScala(akkaExecutor: AkkaExecutionContext): ScalaExecutionContext = new ScalaExecutionContext { | |
def reportFailure(t: Throwable) { | |
akkaExecutor.reportFailure(t) | |
} | |
def execute(runnable: Runnable) { | |
akkaExecutor.execute(runnable) | |
} | |
} | |
/** | |
* convert a scala future to an old style akka future (Which is exactly the same thing!) | |
* @param f | |
* @param akkaExecutor | |
* @tparam T | |
* @return | |
*/ | |
implicit def scalaFutureToAkkaFuture[T](f: ScalaFuture[T])(implicit akkaExecutor: AkkaExecutionContext): AkkaFuture[T] = { | |
implicit val scalaCtx = akkaExCtxToScala(akkaExecutor) | |
val prom = AkkaPromise[T]() | |
f.onComplete { | |
case Success(v) => prom.success(v) | |
case Failure(t) => prom.failure(t) | |
} | |
prom.future | |
} | |
/** | |
* convert an akka future to an old style scala future (Which is exactly the same thing!) | |
* @param f | |
* @param scalaExecutor | |
* @tparam T | |
* @return | |
*/ | |
implicit def akkaFutureToScalaFuture[T](f: AkkaFuture[T])(implicit scalaExecutor: AkkaExecutionContext): ScalaFuture[T] = { | |
implicit val scalaCtx = akkaExCtxToScala(scalaExecutor) | |
val prom = ScalaPromise[T]() | |
f.onComplete { | |
case Right(v: T) => prom.success(v) | |
case Left(t) => prom.failure(t) | |
} | |
prom.future | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment