Convert scala 2.10 future to scalaz.concurrent.Future // Task

一世执手 提交于 2019-12-31 10:42:33

问题


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



来源:https://stackoverflow.com/questions/16895635/convert-scala-2-10-future-to-scalaz-concurrent-future-task

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