pacman pacman - 1 month ago 5
Scala Question

Method onsuccess in Scala Future

I have future that compute some computation and i want to take the result. I have to use variant Await.result(...) (it works fine). But there is onSuccess
method in Future, but it doesn't ensure that i take result before computation finishes. What is purpose and scope of using onSuccess method in Future?


onSuccess is non-blocking.

val f = Future { Thread.sleep(1000) }
f.onSuccess { case _ => println("success" }
println("before success")

This will output:

before success

onSuccess will always be executed when the future successfully completes. The main advantage of this approach is that you are able to move on and do other things while waiting for the future to complete.

With Await.result, it will not move on to the next line until the Future completes.