簡體   English   中英

多個onCompletion適用於Scala的Futures

[英]Multiple onCompletion works in Futures in 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 - 多次回調(相同類型)的執行順序是否確定?

文檔的下一個引用可以回答您的兩個問題:

onComplete,onSuccess和onFailure方法的結果類型為Unit,這意味着無法對這些方法的調用進行鏈接。 請注意,此設計是有意的,以避免暗示鏈式調用可能意味着對已注冊回調的執行進行排序( 在同一個未來注冊的回調是無序的 )。

a1:您可以根據需要注冊多個回調

a2:它們將以“隨機”順序執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM