oncomplete

A look at how exceptions work with Scala Futures and the onComplete ‘Failure’ case alvin September 18, 2017 - 12:53pm

Here’s a little example of how exceptions work with Scala Futures, specifically looking at the onComplete ‘Failure’ case.

In this example I start three Futures that run for different lengths of time, and the shortest-running Future throws an exception:

How to use multiple Futures in a Scala for-comprehension alvin August 22, 2017 - 5:40am

If you want to create multiple Scala Futures and merge their results together to get a result in a for comprehension, the correct approach is to (a) first create the futures, (b) merge their results in a for comprehension, then (c) extract the result using onComplete or a similar technique.

Simple concurrency with Scala Futures (Futures tutorial)

Table of Contents1 - Problem2 - Solution3 - Run one task, but block4 - Run one thing, but don’t block, use callback5 - The onSuccess and onFailure callback methods6 - Creating a method to return a Future[T]7 - How to use multiple Futures in a for loop8 - Discussion9 - A future and ExecutionContext10 - Callback methods11 - For-comprehensions (combinators: map, flatMap, filter, foreach, recoverWith, fallbackTo, andThen)12 - See Also13 - The Scala Cookbook

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 13.9, “Simple concurrency with Scala Futures.”

Back to top

Problem

You want a simple way to run one or more tasks concurrently in a Scala application, including a way to handle their results when the tasks finish. For instance, you may want to make several web service calls in parallel, and then work with their results after they all return.

Back to top

Solution

A Future gives you a simple way to run an algorithm concurrently. A future starts running concurrently when you create it and returns a result at some point, well, in the future. In Scala, it’s said that a future returns “eventually.”

A complete Scala Future example from the Scala Cookbook

There are a number of ways to work with Scala Futures, and I provide examples of those approaches in the Scala Cookbook.

If you’re new to Futures, a fun exercise is to try to determine what happens in your code when you use a certain technique. For instance, when you look at the following Scala source code, what do you think it will print?