foobarbaz
foobarbaz

Reputation: 508

Does scala foreach block?

I can't seem to find any definitive documentation on how foreach should behave in Scala when futures are involved.

For example, in the following snippet:

def someMethod: Future[Int] = {
  val mySeq: Future[Seq[Int]] = Future(Seq(1,2,3,4))
  mySeq.foreach(x => println(x))
  Future(1)
}

Will the Future(1) evaluate only after the foreach completes?

Upvotes: 0

Views: 486

Answers (3)

Mario Galic
Mario Galic

Reputation: 48430

Documentation of Future.foreach states

Asynchronously processes the value in the future once the value becomes available.

Future does not have any blocking methods, except for result and ready which should not be used directly.

Upvotes: 1

Tim
Tim

Reputation: 27421

Future.foreach means "call the following code after the Future completes succesfully". So the println will only be called once mySeq has completed. This might happen before the Future(1) is called, but equally it might not.

Note that Future(Seq(1,2,3,4)) executes asynchronously even though the result is a constant. If you replace this with Future.successful(Seq(1,2,3,4)) then this will complete immediately and the println will happen before the Future(1). However the subsequent foreach call is still asynchronous and may complete after the Future(1)

(Thanks to Thilo for the correction)

Upvotes: 5

Ivan Kurchenko
Ivan Kurchenko

Reputation: 4063

You can take a look at exact method implementation, it looks something like this (in Scala 2.11, but don't think it completely changed over version):

def foreach[U](f: T => U)(implicit executor: ExecutionContext): Unit = onComplete { _ foreach f }

As you may see it is non blocking and will be invoked after Future complete. Essentially it is just syntactic sugar for onComplete.

Hope this help!

Upvotes: 2

Related Questions