如何将Future [Option [(Person,Future [Vector [Order]]]]]]转换为Future [Option [(Person,Vector [Order]]]]]

时间:2019-11-20 20:57:15

标签: scala future

我目前有这个:

def maybePerson(id: Int): Future[Option[Person]] = ???
def orders(personId : Int): Future[Vector[Order]] = ???

val maybePersonAndOrders: Future[Option[(Person, Future[Vector[Order]])]] =
  maybePerson(is = 10).map(_.map { person =>
    (person, orders(person.id))
  })

如何将其转换为(将两个未来合并为一个):

val maybePersonAndOrders: Future[Option[(Person, Vector[Order])]] = ???

1 个答案:

答案 0 :(得分:3)

考虑OptionT monad变压器

(for {
  person <- OptionT(maybePerson(42))
  orders <- OptionT.liftF(orders(person.id))
} yield {
  (person, orders)
}).value

这是一个可行的例子

import cats.data.OptionT
import cats.implicits._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

object OptionTExample extends App {

  case class Person(id: Int, name: String)
  case class Order(personId: Int)

  def maybePerson(id: Int): Future[Option[Person]] = Future(Some(Person(42, "picard")))
  def orders(personId : Int): Future[Vector[Order]] = Future(Vector(Order(personId)))

  val maybePersonAndOrders: Future[Option[(Person, Vector[Order])]] = {
    (for {
      person <- OptionT(maybePerson(42))
      orders <- OptionT.liftF(orders(person.id))
    } yield {
      (person, orders)
    }).value
  }

  maybePersonAndOrders.map(println)
  Thread.sleep(1000)
}

输出

Some((Person(42,picard),Vector(Order(42))))