7

我有几个未来。campaignFuture 返回一个 List[BigInt] 并且我希望能够为从第一个返回的列表中的每个值调用第二个未来 profileFuture。第二个future只能在第一个future完成时调用。我如何在 Scala 中实现这一点?

campaignFuture(1923).flatMap?? (May be?)

def campaignFuture(advertiserId: Int): Future[List[BigInt]] = Future {
  val campaignHttpResponse = getCampaigns(advertiserId.intValue())
  parseProfileIds(campaignHttpResponse.entity.asString)
}

def profileFuture(profileId: Int): Future[List[String]] = Future {
  val profileHttpResponse = getProfiles(profileId.intValue())
  parseSegmentNames(profileHttpResponse.entity.asString)
}    
4

1 回答 1

4

A for comprehension 在这里不适用,因为我们混合了 List 和 Future。所以,你的朋友是 map 和 flatMap:

对未来结果做出反应

  import scala.concurrent.{Future, Promise, Await}
  import scala.concurrent.duration.Duration
  import scala.concurrent.ExecutionContext.Implicits.global

  def campaignFuture(advertiserId: Int): Future[List[BigInt]] = Future {
    List(1, 2, 3)
  }
  def profileFuture(profileId: Int): Future[List[String]] = {
    // delayed Future
    val p = Promise[List[String]]
    Future {
      val delay: Int = (math.random * 5).toInt
      Thread.sleep(delay * 1000)
      p.success(List(s"profile-for:$profileId", s"delayed:$delay sec"))
    }
    p.future
  }



  // Future[List[Future[List[String]]]
  val listOfProfileFuturesFuture = campaignFuture(1).map { campaign =>
    campaign.map(id => profileFuture(id.toInt))
  }

  // React on Futures which are done
  listOfProfileFuturesFuture foreach { campaignFutureRes =>
    campaignFutureRes.foreach { profileFutureRes =>
      profileFutureRes.foreach(profileListEntry => println(s"${new Date} done: $profileListEntry"))
    }
  }


  // !!ONLY FOR TESTING PURPOSE - THIS CODE BLOCKS AND EXITS THE VM WHEN THE FUTURES ARE DONE!!
  println(s"${new Date} waiting for futures")
  listOfProfileFuturesFuture.foreach{listOfFut =>
    Await.ready(Future.sequence(listOfFut), Duration.Inf)
    println(s"${new Date} all futures done")
    System.exit(0)
  }
  scala.io.StdIn.readLine()

一次获得所有期货的结果

  import scala.concurrent.{Future, Await}
  import scala.concurrent.duration.Duration
  import scala.concurrent.ExecutionContext.Implicits.global

  def campaignFuture(advertiserId: Int): Future[List[BigInt]] = Future {
    List(1, 2, 3)
  }
  def profileFuture(profileId: Int): Future[List[String]] = Future {
    List(s"profile-for:$profileId")
  }


  // type: Future[List[Future[List[String]]]]
  val listOfProfileFutures = campaignFuture(1).map { campaign =>
    campaign.map(id => profileFuture(id.toInt))
  }

  // type: Future[List[List[String]]]
  val listOfProfileFuture = listOfProfileFutures.flatMap(s => Future.sequence(s))


  // print the result
  //listOfProfileFuture.foreach(println)
  //scala.io.StdIn.readLine()

  // wait for the result (THIS BLOCKS INFINITY!)
  Await.result(listOfProfileFuture, Duration.Inf)

  • 我们使用Future.sequence将 List[Future[T]] 转换为 Future[List[T]]。
  • flatMap从 Future[Future[T]] 获取 Future[T]
  • 如果您需要等待结果(阻塞!),请使用Await等待结果
于 2014-11-12T07:24:00.907 回答