convert Scala Future to Twitter Future

前端 未结 2 1855
一个人的身影
一个人的身影 2021-02-15 02:26

I use Finagle as a web server which I want to return Scala-Futures from my application logic. How to convert scala.concurrent.Future to com.twitter.util.Future, in a non-blockin

2条回答
  •  清酒与你
    2021-02-15 02:41

    Have not enough environment to test this, but here is what i write for "com.twitter" %% "finagle-http" % "6.25.0":

    import com.twitter.{util => twitter}
    import scala.concurrent.{ExecutionContext, Promise, Future}
    import scala.util.{Failure, Success, Try}
    import language.implicitConversions
    
    object TwitterConverters {
      implicit def scalaToTwitterTry[T](t: Try[T]): twitter.Try[T] = t match {
        case Success(r) => twitter.Return(r)
        case Failure(ex) => twitter.Throw(ex)
      }
    
      implicit def twitterToScalaTry[T](t: twitter.Try[T]): Try[T] = t match {
        case twitter.Return(r) => Success(r)
        case twitter.Throw(ex) => Failure(ex)
      }
    
      implicit def scalaToTwitterFuture[T](f: Future[T])(implicit ec: ExecutionContext): twitter.Future[T] = {
        val promise = twitter.Promise[T]()
        f.onComplete(promise update _)
        promise
      }
    
      implicit def twitterToScalaFuture[T](f: twitter.Future[T]): Future[T] = {
        val promise = Promise[T]()
        f.respond(promise complete _)
        promise.future
      }
    }
    

提交回复
热议问题