这听起来像你想有一个Future
。请参阅AKKA实施here。
一个Future
是一种功能性构造,让你指定的代码块异步执行,然后一旦它完成了,你可以抓住的结果:
import akka.actor.ActorSystem
import akka.dispatch.Await
import akka.dispatch.Future
import akka.util.duration._
implicit val system = ActorSystem("FutureSystem")
val future = Future {
1 + 1
}
val result = Await.result(future, 1 second)
println(result) // prints "2"
您可以用onFailure
指定的故障行为方法(有也是onComplete
和onSuccess
):
val future = Future {
throw new RuntimeException("error")
}.onFailure {
case e: RuntimeException => println("Oops! We failed with " + e)
}
// will print "Oops! We failed with java.lang.RuntimeException: error"
但最好的部分是Future
s为单子,这样你就可以创建异步管道使用的东西的动作像map
和flatMap
:
val f1 = Future { "hello" }
val f2 = f1.map(_ + " world")
val f3 = f2.map(_.length)
val result = Await.result(f3, 1 second)
println(result) // prints "11"
或者在使用它们,内涵:
val f1 = Future { "hello" }
val f2 = Future { " " }
val f3 = Future { "world" }
val f4 =
for (
a <- f1;
b <- f2;
c <- f3
) yield {
a + b + c
}
val result = Await.result(f4, 1 second)
println(result) // prints "hello world"
来源
2012-08-07 05:15:21
dhg
您可以使用在未来的封装本或者你可以使用一个未来的呼叫,看它是否成功或失败。 – 2012-08-07 06:19:40
要么是**真的**不好的模式。 – 2012-08-07 09:16:13
为什么要么是坏模式? – Hakkar 2012-08-07 17:10:19