Accepted answer

This behavior is actually documented for Future.andThen:

Applies the side-effecting function to the result of this future, and returns a new future with the result of this future.

This method allows one to enforce that the callbacks are executed in a specified order.

It means that map will not start its job before the calculations inside andThen are completed. If this is not what you want, you have to call map on the original Future. And then you can use onComplete instead of andThen, so code would become something like this:

  val future = Future {
    println("Started initial Future")

  future onComplete { case Success(value) =>
    println("Started callback")
    println(s"Finished callback: value = $value")

  val f2 = future map { x =>
    println("Chained transformation")
    x * 2

  println(Await.result(f2, Duration.Inf))

P.S. AFAIK there is no standard onComplete equivalent that can be used with method chaining and I think this is by design to make it easier to predict behavior by reading the code. Currently you can use a simple rule: if it is chained - it is executed later.

More Query from same tag