简体   繁体   English

Scala Future的优雅处理[任何一个]

[英]Elegant Handling of Scala Future[Either]]

I have a type whose shape is like this: 我有一个形状如下的类型:

val myType: Future[Either[MyError, TypeA]] = // some value

I know that I could pattern match on this and get to the Right or Left type, but the problem is that I would have to nest my pattern matching logic. 我知道我可以对此进行模式匹配并获得Right或Left类型,但是问题是我必须嵌套我的模式匹配逻辑。 I'm looking for much more elegant way of handling this? 我正在寻找更优雅的方式来处理此问题? Any suggestions? 有什么建议么?

If you encode your MyError as an exception, you don't need the Either anymore and can simply patternMatch against the completion, or use a recoverWith to map it to another type: 如果将MyError编码为异常,则不再需要Either ,而只需针对完成情况进行recoverWith ,或使用recoverWith将其映射为另一种类型:

myType.onComplete {
  case Success(t) =>
  case Failure(e) =>
}

To map your existing Either types you could do something like this: 要映射现有的Either类型,您可以执行以下操作:

case class MyException(e: MyError) extends Exception

def eitherToException[A](f: Future[Either[MyError,A]]): Future[A] = {
  f.flatMap {
    case Left(e) => Future.failed(MyException(e))
    case Right(x) => Future.successful(x)
  }
}

val myType2 = eitherToException(myType)

Alternatively, if MyError and TypeA are under your control, you could create a common super type and pattern match against that: 或者,如果MyErrorTypeA在您的控制之下,则可以创建一个通用的超级类型和模式匹配项:

sealed trait MyResult
final case class MyError() extends MyResult
final case class TypeA() extends MyResult

myType.map {
  case MyError() => ...
  case TypeA() => ...
}

You can create custom extractor objects: 您可以创建自定义提取器对象:

object FullSuccess {
  def unapply[T](x: Try[Either[MyError, T]]) = x match {
    case Success(Right(x)) => Some(x)
    case _ => None
  }
}

object PartSuccess {
  def unapply[T](x: Try[Either[MyError, T]]) = x match {
    case Success(Left(err)) => Some(err)
    case _ => None
  }
}

And

val myType: Future[Either[MyError, TypeA]] = // some value

myType.onComplete {
  case FullSuccess(x) => ... // equivalent to case Success(Right(x))
  case PartSuccess(x) => ... // equivalent to case Success(Left(x))
  case Failure(e) => ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM