Scala future execution

905 views Asked by At

I have two futures. I want to execute them in order. For example:

val ec: ExecutionContextExecutor = ExecutionContext.Implicits.global
val first=Future.successful(...)
val second=Future.successful(...)

When first is completed then second should be executed. The problem is that second should return Future[Object] not Future[Unit] so I can not use completed, andThen etc. functions I can not block the process using await or Thread.sleep(...) I can not use for loop since execution context is defined like this.

first.flatmap( _=> second) will not execute in order. How can I do that?

1

There are 1 answers

0
Simon On

As soon as you assign a Future to a val, that Future is scheduled and will execute as soon as possible. To prevent this you have two options:

  1. Define the Future in a def
  2. Define the Future where you want to use it.

Here's an example of #1:

def first: Future[Int] = Future { Thread.sleep(5000); 1 }
def second(i: Int): Future[Unit] = Future { println(i) }
first.flatMap(i => second(i))

And here's an example of #2:

for(
  i <- Future { Thread.sleep(5000); 1 };
  _ <- Future { println(i) }
) yield ()

Both examples will wait for 5 seconds and print then 1