多个onCompletion适用于Scala的Futures

时间:2016-12-28 10:22:50

标签: scala

在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)
}

//结果

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 

问题2 - 多次回调(同一类型)的执行顺序是否确定?

1 个答案:

答案 0 :(得分:8)

文档中的下一个引文可能会回答您的问题:

  

onComplete,onSuccess和onFailure方法具有结果类型   单位,这意味着无法链接这些方法的调用。注意   这种设计是有意的,以避免暗示链式   调用可能意味着对已注册的执行的命令   回调(在同一个未来注册的回调是无序的)。

a1:您可以根据需要注册多个回调

a2:他们将执行&#34;随机&#34;顺序。