Transform `Future[Option[X]]` into `Option[Future[X]]`
Unfortunately, this isn't possible without losing the non-blocking properties of the computation. It's pretty simple if you think about it. You don't know whether the result of the computation is None
or Some
until that Future
has completed, so you have to Await
on it. At that point, it makes no sense to have a Future
anymore. You can simply return the Option[X]
, as the Future
has completed already.
Take a look here. It always returns Future.successful
, which does no computation, just wraps o
in a Future
for no good reason.
def transform[A](f: Future[Option[A]]): Option[Future[A]] =
Await.result(f, 2.seconds).map(o => Future.successful(o))
So, if in your context makes sense to block, you're better off using this:
def transform[A](f: Future[Option[A]]): Option[A] =
Await.result(f, 2.seconds)
Response for comments:
def transform[A](o: Option[Future[A]]): Future[Option[A]] =
o.map(f => f.map(Option(_))).getOrElse(Future.successful(None))