我希望在两项承诺成功时完成一些行动。所以我创建了这样一段代码:
val promiseForPersistence = Promise[Unit]()
val promiseForReplication = Promise[Unit]()
promiseForPersistence.future.onComplete {
case scala.util.Success(_) => {
if (promiseForReplication.isCompleted) {
println(s"Acking from persistence promise (replication one already completed)" )
}
}
case _ =>
}
promiseForReplication.future.onComplete {
case scala.util.Success(_) => {
if (promiseForPersistence.isCompleted) {
println(s"Acking from replication promise (persistence one already completed)" )
}
}
case _ =>
}
promiseForPersistence.success()
promiseForReplication.success()
问题是,两个日志消息都被打印出来。我希望动作只被触发一次。为什么它会被解雇两次,怎么才能让它开火一次呢?
答案 0 :(得分:5)
为此,您不应在isCompleted
上使用Future
方法。您应该使用flatMap
在一个未来合并2个期货:
for {
_ <- promiseForPersistence.future
_ <- promiseForReplication.future
} println("Both are completed" )
完成两个onComplete
后,可以评估Promise
中的回调。因此,您将在回调和2条isCompleted == true
消息中获得println
。
有效的方法是在回调中添加回调:
promiseForPersistence.future.onSuccess { _ =>
promiseForReplication.future.onSuccess { _ =>
println(s"Acking from replication promise (persistence one already completed)" )
}
}
您将使用flatMap
(for-comprehension
)获得完全相同的行为,但语法更简洁。