使用未来[验证[E,A]]进行理解

时间:2015-12-18 13:09:32

标签: scala scalaz

我想更改一些返回的{api Validation[E,A],这是异步的,理想情况是:Future[Validation[E,A]]。但是我希望能够用它来理解这些。

考虑以下示例:

import scala.concurrent.{Await, ExecutionContext, Future}
import ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scalaz.{Failure, Success, Validation}

def getName : Future[Validation[Int,String]] = {
  Future{
    Success("ed")
  }
}

def useName(name:String) : Future[Validation[Int,String]] = {
  Future{
    Success(s"hi $name")
  }
}


val name : Future[Validation[Int,String]] = getName.flatMap{ v =>
  v match {
    case Success(name) => useName(name)
    case Failure(e) => Future(Failure(e))
  }
}

Await.result(name, 1.second)

要获得name,我需要从验证中获取成功的值,并使用该值调用useName

有没有办法可以按照以下方式做点什么:

val name : Future[Validation[Int,String]] = for{
  n <- getName
  b <- useName(n)
} yield b

就好像我希望理解能够在Future > Validation背景下工作。

我很高兴使用略有不同的类型,我考虑过只使用Future本身的例外情况,但我很想知道上述内容是否可行,而不会发生任何阻塞。

1 个答案:

答案 0 :(得分:4)

我认为唯一的方法就是编写自己的FutureValidation monad:

case class FutureValidation[+E, +A](futval: Future[Validation[E, A]]) {
  def map[B](f: A => B)(implicit executor: ExecutionContext): FutureValidation[E, B] = {
    val result = futval.map { validation =>
      validation.fold(
        fail => Failure(fail),
        succ => Success(f(succ))
      )
    }
    FutureValidation(result)
  }

  def flatMap[EE >: E, B](f: A => FutureValidation[EE, B])(implicit executor: ExecutionContext): FutureValidation[EE, B] = {
    val result = futval flatMap { validation =>
      validation.fold(
        fail => Future(Failure(fail)),
        succ => f(succ).futval
      )
    }
    FutureValidation(result)
  }
}


object FutureValidation {
  def apply[E, A](validation: => Validation[E, A])(implicit executor: ExecutionContext): FutureValidation[E, A] =
    apply(Future(validation))
}

然后你可以有类似的东西:

implicit val e = ExecutionContext.global

val a = scalaz.Success("")
val b = Future(scalaz.Success(""))

for {
  r1 <- FutureValidation(a)
  r2 <- FutureValidation(b)
} yield r2