我有这样的代码示例
val request: Defered[Int] = client.getSomeIntAsynFromSocket();
request.addCallBack(result => result.success[String])
request.addErrback(error => error.fail[Integer])
如何从deferred'request'和可用的回调中构造Future [Validation [String,Int]]
============================================== < / p>
我自己的解决方案:
val f = Future {
val queue = java.util.concurrent.ArrayBlockingQueue[Validation[String, Int]](1)
val request: Defered[Int] = client.getSomeIntAsynFromSocket();
request.addCallBack(result => queue.add(result.success[String]))
request.addErrback(error => queue(error.fail[Integer]))
f.take
}
答案 0 :(得分:4)
对于Akka 2.x,将方法放在某处,您可以通过导入重复使用它。
def asFuture[T](d: Defered[T])(implicit e: ExecutionContext): Future[T] = {
val p = Promise[T]()
d.addCallback(r => p tryComplete Right(r))
d.addErrback(e => p tryComplete Left(e))
p.future
}
val f = asFuture(client.getIntAsynFromSocket())