scala中的理解半并行调用

For-comprehension semi-parallel calls in scala

我想在 seq 中对下一个调用进行第一次调用,然后使用 Scala 的 futures 相互并行调用接下来的 10 个调用。我不想对地图平面图或内部进行编程以进行理解,因为它们会增加不可读性。有没有办法理解一下。

参考代码:

val fcaAndFplAccountDetails  = getFcaAndFplAccount(fplId)
def orgDetailsIO(orgId:Int)  = getOrgDetails(orgId)
def unbilledTxns(orgid: Int) = getUnbilledTxns(orgId)
for {
      accDetails   <- fcaAndFplAccountDetails
      orgDetails   <- orgDetailsIO(accDetails.orgId)
      unbilledTxns <- unbilledTxnsIO(accDetails.orgId)
      ... other calls that depend on org id
    } yield { ... further computations }

fcaAndFplAccountDetails之后的调用能否在理解范围内并行化?

肯定有几十种选择,但一个是:

  val fcaAndFplAccountDetails : Future[Int] = ???
  def orgDetailsIO(orgId:Int)  : Future[_] = ???
  def unbilledTxns(orgid: Int) : Future[_] = ???
  for {
    accDetails   <- fcaAndFplAccountDetails
    (orgDetails, unbilledTxns)   <- Future.sequence(List(orgDetailsIO(accDetails), unbilledTxns(accDetails))).map(el => (el(0), el(1)))
} yield ()

你也可以使用 Future.traverse

也许跟随一个带有值定义的生成器,使用等号来表示应该并行执行的调用

for {
  accDetails    <- fcaAndFplAccountDetails
  orgDetailsF   = orgDetailsIO(accDetails.orgId)
  unbilledTxnsF = unbilledTxnsIO(accDetails.orgId)
  orgDetails    <- orgDetailsF
  unbilledTxns  <- unbilledTxnsF 
} yield { ... further computations }

或用Applicative

表达想法
import cats.implicits._

fcaAndFplAccountDetails.flatMap { accDetails =>
  (
    orgDetailsIO(accDetails.orgId),
    unbilledTxnsIO(accDetails.orgId)
  ).mapN((orgDetails, unbilledTxns) => {
    ... further computations  
  }
}