pacman pacman - 1 year ago 84
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download