gpt4 book ai didi

Scala Future onComplete 回调不会立即执行

转载 作者:行者123 更新时间:2023-12-04 17:21:29 25 4
gpt4 key购买 nike

我有一个 Future[Future[Set[String]]。我将其平面化以返回 Future[Set[String]]。我等待无穷大(我知道这很糟糕)然后检查 Future 是否完成。它返回真。但是,当我获取 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

最佳答案

您需要将 Await.result(criteriaValueList, scala.concurrent.duration.Duration.Inf) 的输出分配给一个值。目前您正在等待它完成,不对输出执行任何操作,然后将 onComplete 回调附加到已经完成的 future ,然后您的程序在回调运行之前终止。

val segmentNames = Await.result(criteriaValueList, scala.concurrent.duration.Duration.Inf)
log.info("Google Segments = " + segmentNames.mkString(","))

关于Scala Future onComplete 回调不会立即执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27385463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com