I'm going through some Future examples. I have a Future which retrieves a list from a method. I call two different kinds of callbacks, a Foreach callback and an onComplete callback just to try them out.
- The Foreach callback nearly every time returns the list.
- The onComplete callback rarely returns SUCCESS even though the For callback has returned the list.
- The onComplete callback never returns FAILURE.
Can someone please explain to me what's happening?
I understand that the callbacks do execute concurrently, and do not have an order. But if the Future is returning the list to Foreach andthe onComplete callback has executed before the Foreach and Future and it tried to get the list from an unsuccessful Future, shouldn't the onComplete callback return FAILURE?
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}
object FuturesExampleObj extends App {
println("Using Future to retrieve list\n")
val l: Future[List[String]] = Future {
getList()
}
println("FOR CALLBACK --------------------\n")
l foreach {
items =>
for(item <- items) println(s"foreach item : $item")
println("\n")
}
println("onComplete CALLBACK --------------------\n")
l onComplete {
case Success(i) => println(s"SUCCESS : $i")
case Failure(i) => println(s"FAILURE : $i")
}
def getList(): List[String] ={
val list = ("a" :: "b" :: "c" :: "d" :: "e":: Nil)
list
}
}
Result Example 1 (Common)
Using Future to retrieve list
FOR CALLBACK --------------------
onComplete CALLBACK --------------------
foreach item : a
foreach item : b
foreach item : c
foreach item : d
foreach item : e
Process finished with exit code 0
Result Example 2 (uncommon)
Using Future to retrieve list
FOR CALLBACK --------------------
onComplete CALLBACK --------------------
Process finished with exit code 0
Result Example 3 (very rare)
Basically onComplete never returns SUCCESS or FAILURE. On occasion, very rarely, it will return "SUCCESS: " + list.