Promise for better Future

Scala Futures

(λx.x)eranga
Effectz.AI
2 min readAug 6, 2019

--

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.

Helper functions

Following are some helper functions that I’m using in this post. These functions return various type of futures.

onComplete()

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()

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 Try.

recover()

To handle the errors on future recover() function can be used. It can be used to return default value on future error.

recoverWith()

As same as recover(), 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()

With fallbackTo() function we can define alternative method to execute when future failed.

map()

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()

Unlike map(), 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).

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.

sequence()

Future.sequence() function will convert Seq[Future[T]] to Future[Seq[T]]. These futures will be run parallelly(which differs from for-yield) and aggregate the result into single Future[Seq[T]].

zip()

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 future

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 recover function.

Reference

  1. http://allaboutscala.com/tutorials/chapter-9-beginner-tutorial-using-scala-futures/#chain-futures-using-flatmap
  2. https://www.credera.com/blog/credera-site/mastering-scala-futures/
  3. https://blog.knoldus.com/futures-with-timeout-in-scala/
  4. https://danielwestheide.com/blog/2013/01/09/the-neophytes-guide-to-scala-part-8-welcome-to-the-future.html
  5. https://hello-scala.com/920-scala-futures.html

--

--