在并发Future中建立API调用,和主线程并发地执行任务
/*
调用远程API,获得传入城市的温度
*/
def cityTemp(name:String):Double = {
val url = "http://api.openweathermap.org/data/2.5/weather"
val cityUrl = s"$url?q=$name&APPID=981224145dabaaf57b51ff469e7f1acd"
val json = io.Source.fromURL(cityUrl).mkString
val pattern = """.*"temp":([\d]+).*""".r
val pattern(temp) = json
temp.toDouble
}
import concurrent.Future
import concurrent.ExecutionContext.Implicits.global
import scala.util.Success
def main(args:Array[String]):Unit = {
//调用Future.sequence 并发执行Future
val cityTemps:Future[Seq[Double]] = Future sequence Seq(
Future(cityTemp("Fresno")),Future(cityTemp("Tempe"))
)
//Future回调函数,当Future执行完成,会自动调用这个函数,输出函数结果
cityTemps onComplete {
case Success(Seq(x, y)) if x > y => println(s"Fresno is warmer: $x K")
case Success(Seq(x, y)) if y > x => println(s"Tempo is warmer: $y K")
}
//OnComplete调用对变量的影响
var temp = 0.0d;
cityTemps onComplete {
case Success(Seq(x, y)) if x > y => temp = x
case Success(Seq(x, y)) if y > x => temp = y
}
//主线程继续执行,为了看到OnComplete的执行结果,等待10秒
//temp before complete: 0.0
println("temp before complete: " + temp)
Thread.sleep(10000)
//temp after complete: 294.0
println("temp after complete: " + temp)
println("result complete")
}