Angle Tom
Angle Tom

Reputation: 1130

scala future and promise didn't return result as expected

I 'm a beginner for scala. I execute some code as follows. I think the result will be "Hello1".

val testFuture: Future[Seq[String]] = Future {
   var res = Seq.empty[String]
    res = res :+ "hello1"
    res
}
val testFuture1:Future[Seq[String]] = Future {
     var test = Seq.empty[String]
     test = test :+ "kkkkkkkkk"
     test
}

val result = for {
    restFu1 <- testFuture
    restFu2 <- testFuture1
   if(restFu1 != restFu2)
} yield restFu1

result onSuccess {
   case result => println("***************"+ result)
}
result onFailure {
  case _ => println ("************ fail........" )
 }

But in fact, the result is nothing. anyone knows the reason.

Upvotes: 0

Views: 83

Answers (2)

Tim
Tim

Reputation: 2028

If you run it in REPL you'll get the result you expect

scala> ***************List(hello1)

If you run it from an IDE, then likely you will not see the output, because Future is scheduled on a separate thread and your program is terminated before that thread had a chance to run. There are a couple ways to prevent program termination in this case:

val res = Await.result(result, 1 second)
// or
val cbF = result onSuccess {
  case result => println("***************"+ result)
 }
Await.ready(cbF, 1 second)

Note that in the first case you actually get the result and don't need to schedule a callbackso you'll need your println in the main program flow. In the second case, you're only interested in the side-effect, so ready method is used instead. Note that in order to guarantee the println execution you need to await on the callback future.

Finally, using Await for testing/learning is fine, but using it in production code is generally a bad idea.

Upvotes: 1

grotrianster
grotrianster

Reputation: 2468

When you using Future you are actually running computation in another thread, while the main thread of you program just starts them and then as there is nothing to do main thread exit and program terminates, just put Thread.sleep and the end of you program to make main thread wait for a 1 second and you should see result

Thread.sleep(1000) 

Upvotes: 0

Related Questions