が欲しいようですねFuture
。ここで AKKA の実装を参照してください。
AFuture
は、非同期に実行するコード ブロックを指定できる関数構造であり、完了したら結果を取得できます。
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"
しかし、最良の部分はs がモナドであるため、や などFuture
を使用して非同期アクションのパイプラインを作成できることです。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"
または、それらを for 内包表記で使用します。
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"