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

后端 未结 2 2021
野的像风
野的像风 2021-02-03 09:53

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,

相关标签:
2条回答
  • 2021-02-03 10:38

    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.

    0 讨论(0)
  • 2021-02-03 10:38

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

    0 讨论(0)
提交回复
热议问题