将 scala 2.10 future 转换为 scalaz.concurrent.Future//任务 [英] Convert scala 2.10 future to scalaz.concurrent.Future // Task

查看:50
本文介绍了将 scala 2.10 future 转换为 scalaz.concurrent.Future//任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人来过一段代码如何正确地将scala的未来(2.10)转换为新的scalaz7未来?我知道通过 scala Promise 将 scalaz future 转换为 scala Future 很热,但不确定如何正确地在

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

例如

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

我想实现

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 :-)

推荐答案

在评估了几个替代方案后,我得出了以下解决方案.显然,如果有人想要scalaz.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 是要走的路.

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

}

然而,一旦转换为 Scala 未来,此解决方案也会运行任务,这可能/可能不需要,具体取决于情况.

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

这篇关于将 scala 2.10 future 转换为 scalaz.concurrent.Future//任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆