2

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?

Luciano van der Veekens
  • 6,307
  • 4
  • 26
  • 30
gg gg
  • 129
  • 7
  • 3
    just make `second` a `def` instead of a `val`? – Sascha Kolberg Sep 06 '17 at 08:50
  • Maybe you can use some polling of first `Future` for completion, and when it is completed run the second one. – SergeiK Sep 06 '17 at 08:52
  • 1
    following @SaschaKolberg's suggestion, try defining both `first` and `second` as `def` rather than `val`, then `first.flatmap( _=> second)` will complete the two futures sequentially and in order. (there's no great need to define `first` as a `def`, but for symmetry it seems nice. if first is `def`, and reference to first will re-excute `Future.successful(...)`.) – Steve Waldman Sep 06 '17 at 09:19
  • It did not work since when second takes the first value, it returns. It will not wait until first finishes. – gg gg Sep 06 '17 at 09:26

1 Answers1

2

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

Simon
  • 6,293
  • 2
  • 28
  • 34