本文主要是介绍Scala Future OnComplete调用 笔记,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在并发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).mkStringval pattern = """.*"temp":([\d]+).*""".rval pattern(temp) = jsontemp.toDouble}
import concurrent.Future
import concurrent.ExecutionContext.Implicits.global
import scala.util.Successdef main(args:Array[String]):Unit = {//调用Future.sequence 并发执行Futureval 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 = xcase Success(Seq(x, y)) if y > x => temp = y}//主线程继续执行,为了看到OnComplete的执行结果,等待10秒//temp before complete: 0.0println("temp before complete: " + temp)Thread.sleep(10000)//temp after complete: 294.0println("temp after complete: " + temp)println("result complete")}
这篇关于Scala Future OnComplete调用 笔记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!