Scala Futures: simple Explanation with Examples

Last updated:

WIP Alert This is a work in progress. Current information is correct but more content will probably be added in the future.

Intro

TODO

Wrapping something in a Future

It might take a very long time to fetch a User from the database (suppose we are using a distributed database so it might take anywhere from a milisecond (cache hit) to a few seconds) so we wrap it in a Future so that whoever is using this method knows that this might take some take so they can press on with other computations while this get processed.

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global

//note the type declaration, Future[User]
def getUserFromUsername(name: String): Future[User] = {
    Future{
        DB.findUserByUsername(name) //returns a User, eventually
    }
}

Composing Futures with map and flatMap

  • map

    • Execute a synchronous operation after a Future is complete
  • flatMap

    • Execute another Future after the first is complete

Running many futures concurrently using for-comprehensions

TODO

Map or catch errors in a Future

TODO (use recover)

See also

Dialogue & Discussion