我有一个未来[未来[Set [String]]。我将它平面映射以返回Future [Set [String]]。我等待无限(我知道这很糟糕),然后检查未来是否完整。它返回true。但是,当我获得Future返回的值并尝试将其添加到Set时,它不会添加它。首先打印回调结束时的语句。当我从方法返回Set时,虽然Future确实返回值,但它总是为空。我添加了注释来解释发生的事件顺序。如果我做错了,请指出我!谢谢!
val googleXfpSegments = Set[String]()
val customCriteriaFuture: Future[List[Long]] = getCustomCriteriaValueIds(lineItemPage.getResults())
// getCustomCriteriaValues returns a Future[Set[String]]
val criteriaValueList = customCriteriaFuture.flatMap(criteriaIdList => getCustomCriteriaValues(criteriaIdList.toSet))
// I wait for infinite time
Await.result(criteriaValueList, scala.concurrent.duration.Duration.Inf)
log.info("Future Completed = " + criteriaValueList.isCompleted) // This returns true
criteriaValueList onComplete {
case Success(segmentNames) => {
// This statement gets printed after the "TEST" value gets printed
log.info("SegmentNameList = " + segmentNames.mkString(","))
googleXfpSegments ++= segmentNames
// This prints nothing which means the segmentNames is not getting added
log.info("Google Segments = " + googleXfpSegments.mkString(","))
}
case Failure(error) => log.error("Error occurred ", error)
}
googleXfpSegments += "TEST"
// This prints TEST
log.info("Google Segments = " + googleXfpSegments.mkString(","))
日志输出如下所示:
[info] [INFO] [2014-12-09 17:25:01,147] [service.GoogleXFPService] Future Completed = true
[info] [INFO] [2014-12-09 17:25:01,148] [service.GoogleXFPService] Google Segments = TEST
[info] [INFO] [2014-12-09 17:25:01,148] [service.GoogleXFPService] SegmentNameList = vt.cm,vt.cp,ex.qy,ex.ahe,cm.gannett_trav
答案 0 :(得分:4)
您需要将Await.result(criteriaValueList, scala.concurrent.duration.Duration.Inf)
的输出分配给值。目前,您正在等待它完成,不对输出执行任何操作,然后将onComplete回调附加到已完成的将来,然后您的程序在回调可以运行之前终止。
val segmentNames = Await.result(criteriaValueList, scala.concurrent.duration.Duration.Inf)
log.info("Google Segments = " + segmentNames.mkString(","))