Scala: ExecutionContext for future understanding

When I do future or apply methods such as onSuccess and map , I can specify ExecutionContext for them.

For example,

 val f = future { // code } executionContext f.map(someFunction)(executionContext) f onSuccess { // code } executionContext 

However, if I use for-comprehension of future, how can I specify an ExecutionContext for the yield part?

 for { f <- future1 g <- future2 } yield { // code to be executed after future1 onSuccess and future2 onSuccess // What ExecutionContext runs this code? } // (executionContext) here does not work 

And what does the ExecutionContext run the code in the lesson if not specified?

<h / "> EDIT

OK Thanks to the answers, I found something.
Unless I define or import an implicit ExecutionContext (for example, Implicits.global ), Understanding does not compile. This means that an implicit ExecutionContext is used for understanding.

Then, how can I use for-comprehension without an implicit ExecutionContext, i.e. how to specify?

+7
scala future for-comprehension
source share
2 answers

The ExecutionContext parameter is actually implicit . This means that you can:

 import scala.concurrent.ExecutionContext implicit val context = ExecutionContext.fromExecutor(//etc) for { f <- future1 g <- future2 } yield { // code to be executed after future1 onSuccess and future2 onSuccess // What ExecutionContext runs this code?: the one above. } 

You also have a default value, namely scala.concurrent.ExecutionContext.Implicits.global . It has as many threads as there are processors on a running machine.

It will not be used by all futures by default, you still have to import it.

Refresh . If you really want to specify, although this is not recommended, you can expand for yield

 val combined = futureA.flatMap(x => futureB)(context) 
+8
source share

Since for methods are "mapped" to map / flatMap , and the ExecutionContext parameters are implicit, I think you can try adding implicit val to the local scope:

implicit val myContext:ExecutionContext = ...

.

I do not believe that there is an implicit ExecutionContext , but the most commonly used ExecutionContext.Implicits.global .

+1
source share

All Articles