I have the following test code snippet:
import scala.concurrent.{Await, Future}
import scala.concurrent.duration.Duration
import scala.util.Success
import scala.concurrent.ExecutionContext.Implicits.global
object FutureAndThen extends App {
val future = Future {
println("Started initial Future")
10
} andThen { case Success(value) =>
println("Started callback")
Thread.sleep(5000)
println(s"Finished callback: value = $value")
} map { x =>
println("Chained transformation")
x * 2
}
println(Await.result(future, Duration.Inf))
}
It produces the following output:
Started initial Future
Started callback
Finished callback: value = 10
Chained transformation
20
I expect andThen
callback to be executed asynchronously. But the actual execution is the next:
- Execute original future
- Execute asynchronous callback
- Run transformations (
map
)
At first I thought that the issue is in ExecutionContext
which decided to run all these operations in single thread. And I changed this to use custom ExecutionContext
:
implicit val ctx = ExecutionContext.fromExecutor(
(command: Runnable) => new Thread(command).start()
)
And the result is the same. Could you advice me what I am missing?