在Scala中试用Futures时,我注意到对OnCompletion的多次调用都有效!
问题1 - 显然,我不应该以这种方式编写代码,但我想知道编译器是否应该在这种情况下引发错误?
import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure,Success}
object ConcurrencyExample extends App {
val time = System.currentTimeMillis()
println("looking at inventory")
//create code we want to execute concurrently
val f: Future[Int] = Future //or just f = Future
{
println("add item to shopping basket")
Thread.sleep(30) //simulate backend process delay
println("Item added")
1 //simulate the no. of items in basket
}
//this works
f onComplete (x => println("on complete1 " + x))
//and this too
f onComplete {
case Success(value) => println("on complete2 size of basket" + value)
case Failure(e) => println(e)
}
//this is called as well though I do not see problem in this as I can segregate the code for completion, success and failure
f onSuccess {
case v => println("on success size of basket"+v)
}
f onFailure {
case e => println("on failure. Reason"+e)
}
for (i<- 1 to 5)
{
println("looking at more items in inventory ")
Thread.sleep(10)
}
Thread.sleep(500)
}
Run Code Online (Sandbox Code Playgroud)
//结果
looking at inventory
add item to shopping basket
looking at more items in inventory
Item added
on success size of basket1
**on complete2 size of basket1
on complete1 Success(1)**
looking at more items in inventory
looking at more items in inventory
looking at more items in inventory
looking at more items in inventory
Run Code Online (Sandbox Code Playgroud)
问题2 - 多个回调(相同类型)的执行顺序是否确定?
文档的下一个引用可以回答您的两个问题:
onComplete,onSuccess和onFailure方法的结果类型为Unit,这意味着无法对这些方法的调用进行链接.请注意,此设计是有意的,以避免暗示链式调用可能意味着对已注册回调的执行进行排序(在同一个未来注册的回调是无序的).
a1:您可以根据需要注册多个回调
a2:它们将以"随机"顺序执行.
| 归档时间: |
|
| 查看次数: |
976 次 |
| 最近记录: |