`Future[Option[Future[Option[X]]]]` 转换成 `Future[Option[X]]` [英] `Future[Option[Future[Option[X]]]]` into `Future[Option[X]]`
问题描述
如何将Future[Option[Future[Option[X]]]]
转化为Future[Option[X]]
?
如果它是 TraversableOnce
而不是 Option
我会使用 未来伴侣对象;但是选项呢?
If it were a TraversableOnce
instead of Option
I'd use the Future companion object; but what about Options?
示例:
def processAndReturnFuture(x:String):Future[String] = future(x)
def processAgainAndReturnOption(x:String):Option[String] = Some(x)
val futOpt:Future[Option[String]] = future(Some("x"))
val futOptFutOpt:Future[Option[Future[Option[String]]]] =
futOpt.map( opt =>
opt.map( x =>
processAndReturnFuture(x).map( processedX =>
processAgainAndReturnOption(processedX)
)
)
)
推荐答案
更新答案
这可能会奏效.我所做的是用最外层 Future
上的 flatMap
和最外层 Option 上的模式匹配替换前两个
map
调用代码>.
Updated answer
This might do the trick. What I did was to replace your first two map
calls with a flatMap
on the outermost Future
and a pattern match on the outermost Option
.
val futOptFutOpt: Future[Option[String]] =
futOpt.flatMap {
case None => Future.successful(None)
case Some(x) =>
processAndReturnFuture(x).map {
processedX => processAgainAndReturnOption(processedX)
}
}
初步回答
我假设在你的代码中你有一个 map
调用,它把一个 Future[Option[A]]
转换成一个 Future[Option[Future[Option][X]]]]
.将 map
替换为 flatMap
并在结果中删除最顶层的 Option
层.你最终会得到 Future[Option[X]]
.这就是我的意思:
Initial answer
I presume somewhere in your code you have a map
call that transforms a Future[Option[A]]
into a Future[Option[Future[Option[X]]]]
. Replace that map
with a flatMap
and drop the top-most Option
layer in the result. You'll end up with Future[Option[X]]
. Here's what I mean:
scala> import scala.concurrent._
import scala.concurrent._
scala> import ExecutionContext.Implicits.global
import ExecutionContext.Implicits.global
scala> val f1: Future[Option[Future[Option[String]]]] =
| Future.successful(Some(1)).map(v => Some(Future.successful(Some(v.toString))))
f1: scala.concurrent.Future[Option[scala.concurrent.Future[Option[String]]]] = scala.concurrent.impl.Promise$DefaultPromise@6f900132
scala> val f2: Future[Option[String]] =
| Future.successful(Some(1)).flatMap(v => Future.successful(Some(v.toString)))
f2: scala.concurrent.Future[Option[String]] = scala.concurrent.impl.Promise$DefaultPromise@2fac9a62
对于您的实际上下文,我可能并不完全正确,但您可能会通过用几个 flatMap
替换几个 map
来解决这个问题.
I'm probably not entirely correct as to what your actual context is, but you'll probably solve this by replacing a few map
s with a few flatMap
s.
这篇关于`Future[Option[Future[Option[X]]]]` 转换成 `Future[Option[X]]`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!