convert Scala Future to Twitter Future

半世苍凉 提交于 2019-12-09 10:13:58

问题


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-blocking way of course?


回答1:


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
  }
}



回答2:


It's also possible to use Twitter bijections library: https://github.com/twitter/bijection

Namely com.twitter.bijection.twitter_util.UtilBijections (https://github.com/twitter/bijection/blob/develop/bijection-util/src/main/scala/com/twitter/bijection/twitter_util/UtilBijections.scala)

This library handles important details, for example if you convert object forth and back, it just unwraps original object.




回答3:


Here's an example using the twitter bijection library:

import scala.concurrent.{Future => ScalaFuture}
import com.twitter.util.{Future => TwitterFuture}

// extend values by adding the conversion method "as"
import com.twitter.bijection.Conversion.asMethod

// pull in various implicit converters that "as" expects, 
// including twitter2ScalaFuture:
import com.twitter.bijection.twitter_util.UtilBijections._

def doSomething: ScalaFuture[T] = {
    val response: TwitterFuture[T] = ???
    response.as[ScalaFuture[T]]
}


来源:https://stackoverflow.com/questions/30317473/convert-scala-future-to-twitter-future

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!