In this post I’m gonna discuss about various operations that can be performed with scala
Futures. All the source codes which related to this post available on gitlab. Please clone the repo and continue the post.
Following are some helper functions that I’m using in this post. These functions return various type of futures.
Future.onComplete() allows us to define callback functions, which execute upon a Future’s success or failure. Once future completes its operation, onComplete executes asynchronously (its a non blocking operation).
Await.result() blocks the further operations until future completes its operation. The
timeout defines waiting time to finish the future execution. To handle the errors future result can be wrapped with
To handle the errors on future
recover() function can be used. It can be used to return default value on future error.
As same as
recoverWith() function also can be used to handle the errors in future. Main difference on recoverWith is, it executes another future operation after failure.
fallbackTo() function we can define alternative method to execute when future failed.
map() function can used to access the value returning from the future and do some operation on it. The output will be an another future.
flatMap() requires to returns the value wrapping it in a Future. Also it can be used to obtain single future from nested futures(similar to handle future chain).
We can handle chain of futures and merge their results together by using
for yield or
flatMap. These futures will be run sequentially one after another.
Future.sequence() function will convert
Future[Seq[T]]. These futures will be run parallelly(which differs from
for-yield) and aggregate the result into single
Future.zip() function combine the results of two future operations into a single tuple. It creates a new future with return type of tuple(tuple holds return type of two futures).
Akka ask will sends a message to
Actor and returns a future. When timeout occurs it throws
akka.pattern.AskTimeoutException. We can asynchronously handle this future and obtain the result by using
map function. To handle the future timeout we can use