简体   繁体   English

Scala:ExecutionContext,用于未来的理解

[英]Scala: ExecutionContext for future for-comprehension

When I make a future , or apply methods like onSuccess and map , I can specify ExecutionContext for them. 当我创建future ,或应用onSuccessmap等方法时,我可以为它们指定ExecutionContext。

For example, 例如,

val f = future {
  // code
} executionContext

f.map(someFunction)(executionContext)

f onSuccess {
  // code
} executionContext

However, if I use a for-comprehension of future, how can I specify ExecutionContext for the yield part? 但是,如果我使用了对未来的理解,我如何为yield部分指定ExecutionContext?

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 ExecutionContext runs the code in yield if not specified? 而且,如果没有指定,ExecutionContext在yield中运行代码是什么?


EDIT 编辑

OK. 好。 Thanks to answers, I found something. 感谢答案,我找到了一些东西。
If I don't define or import implicit ExecutionContext (like Implicits.global ), the for-comprehension does not compile. 如果我没有定义或导入隐式 ExecutionContext (如Implicits.global ),则for-comprehension不会编译。 That means, for-comprehension uses implicit ExecutionContext. 这意味着,for-comprehension使用隐式ExecutionContext。

Then, how can I use for-comprehension without implicit ExecutionContext, ie how to specify? 那么,如何在没有隐式ExecutionContext的情况下使用for-comprehension,即如何指定?

The ExecutionContext parameter is actually implicit . ExecutionContext参数实际上是implicit That means 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, namely scala.concurrent.ExecutionContext.Implicits.global . 您还有一个默认值,即scala.concurrent.ExecutionContext.Implicits.global This has as many threads as the processors on the running machine. 它具有与正在运行的计算机上的处理器一样多的线程。

It won't be used by all Futures by default, you still have to import it. 默认情况下,所有期货都不会使用它,您仍然需要导入它。

Update : If you really want to specifiy, although it's not recommended, you can unwrap the for yield 更新 :如果你真的想要指定,虽然不推荐,你可以打开for yield

val combined = futureA.flatMap(x => futureB)(context)

Since for comprehensions are "mapped" to map / flatMap operations, and the ExecutionContext parameters of those are implicit, I guess you can try to add an implicit val in the local scope: 由于for内涵的“映射”来map / flatMap操作和ExecutionContext的参数是隐含的,我想你可以尝试添加一个implicit val在局部范围内:

implicit val myContext:ExecutionContext = ...

.

I don't believe there is a "default" implicit ExecutionContext , but the most commonly used one is ExecutionContext.Implicits.global . 我不相信存在“默认”隐式ExecutionContext ,但最常用的是ExecutionContext.Implicits.global

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM