使用 andThen 强制保证 future 的执行顺序
一个 future 可以绑定多个 onComplete。然而,上下文环境并不会保证哪个 future 的 onComplete 会被率先触发,而 andThen 方法保证了回调函数的执行顺序。
package Option.test
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.Success
object andThen1 {
def main(args: Array[String]): Unit = {
val intFuture = Future {
Thread.sleep(2000)
println(Thread.currentThread().getName)
200
}
// 主程序的 onComplete 方法的调用顺序不一定
intFuture onComplete {
case Success(int) => println(s"this future returned $int")
case _ => println("something wrong has happened.")
}
intFuture onComplete {
case Success(int) => println(s"completed with the value of $int")
case _ => println("something wrong has happened.")
}
Thread.sleep(3000)
}
}
执行上述的程序,控制台有可能先打印 this future returned $int ,也有可能先打印 completed with the value of $int 。
package Option.test
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.Success
object andThen1 {
def main(args: Array[String]): Unit = {
val intFuture = Future {
Thread.sleep(2000)
println(Thread.currentThread().getName)
200
}
// 主程序的 onComplete 方法的调用顺序不一定
intFuture onComplete {
case Success(int) => println(s"this future returned $int")
case _ => println("something wrong has happened.")
}
intFuture andThen {
case Success(int) => println(s"completed with the value of $int")
case _ => println("something wrong has happened.")
}
Thread.sleep(3000)
}
}
andThen 方法会返回原 future 的一个镜像,并且只会在该 future 调用完 onCompelete 方法之后,andThen 才会执行。