两个承诺完成时的消防行动

时间:2014-01-01 19:15:51

标签: scala promise

我希望在两项承诺成功时完成一些行动。所以我创建了这样一段代码:

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()

问题是,两个日志消息都被打印出来。我希望动作只被触发一次。为什么它会被解雇两次,怎么才能让它开火一次呢?

1 个答案:

答案 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)" )
  }
}

您将使用flatMapfor-comprehension)获得完全相同的行为,但语法更简洁。