Convert scala 2.10 future to scalaz.concurrent.Fut

2019-03-11 06:09发布

问题:

did anybody come to piece of code how to properly convert scala's Future (2.10) to new scalaz7 future ? I know hot to convert scalaz future via scala Promise to scala Future, but not sure how to do it properly around

For example

import scalaz.concurrent.{Future => Zuture}
import scala.concurrent.Future

I want to have implementation of

implicit def scalaF2scalazF[A](in:Future[A]):Zuture[A]=???

Then obviously would be piece of cake to write

implicit def scalaF2scalazTask[A](in:Future[A]):Task[A]=???

because thats is what I really want :-)

回答1:

After evaluating couple of alternatives I have come to following solution. Obviously if someone wantsscalaz.Monad[scala.concurrent.Future], scalaz.std.scalaFuture https://github.com/scalaz/scalaz/blob/series/7.2.x/core/src/main/scala/scalaz/std/Future.scala#L85 is the way to go.

object ScalaFutureConverters {


  implicit def scalaFuture2scalazTask[T](fut: Future[T])(implicit ec: ExecutionContext): Task[T] = {
    Task.async {
      register =>
        fut.onComplete {
          case Success(v) => register(v.right)
          case Failure(ex) => register(ex.left)
        }
    }
  }


  implicit def scalazTask2scalaFuture[T](task: Task[T]): Future[T] = {
    val p: Promise[T] = Promise()

    task.runAsync {
      case -\/(ex) => p.failure(ex)
      case \/-(r) => p.success(r)
    }

    p.future
  }


  implicit class ScalazFutureEnhancer[T](task: Task[T]) {
    def asScala: Future[T] = scalazTask2scalaFuture(task)
  }


  implicit def scalaF2EnhancedScalaF[T](fut: Future[T])(implicit ec: ExecutionContext): ScalaFEnhancer[T] =
    ScalaFEnhancer(fut)(ec)

  case class ScalaFEnhancer[T](fut: Future[T])(implicit ec: ExecutionContext) {
    def asTask: Task[T] = scalaFuture2scalazTask(fut)(ec)
  }

}

This solution however also runs the task once the conversion to scala future is made which may/may not be desired, depending on situation.



回答2:

You can also use https://github.com/Verizon/delorean which adds convenient toTask and toFuture methods