Reputation: 129
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?
Upvotes: 2
Views: 966
Reputation: 6363
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:
Future
in a def
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
Upvotes: 2