问题描述
当我制作future
或应用onSuccess
和map
之类的方法时,我可以为其指定ExecutionContext.
When I make a future
, or apply methods like onSuccess
and map
, I can specify ExecutionContext for them.
例如,
val f = future {
// code
} executionContext
f.map(someFunction)(executionContext)
f onSuccess {
// code
} executionContext
但是,如果我对未来有所了解,如何为yield
部分指定ExecutionContext?
However, if I use a for-comprehension of future, how can I specify 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
而且,如果未指定,什么ExecutionContext可以在yield中运行代码?
And, what ExecutionContext runs the code in yield if not specified?
编辑
好.多亏了答案,我发现了一些东西.
如果我没有定义或导入 隐式 ExecutionContext (例如Implicits.global
),理解不能编译.这意味着,理解会使用隐式的ExecutionContext.
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. That means, for-comprehension uses implicit ExecutionContext.
然后,如何在没有隐式ExecutionContext的情况下使用理解功能,即如何指定?
Then, how can I use for-comprehension without implicit ExecutionContext, i.e. how to specify?
推荐答案
ExecutionContext
参数实际上是implicit
.这意味着您可以:
The ExecutionContext
parameter is actually 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.
}
您也有一个默认值,即scala.concurrent.ExecutionContext.Implicits.global
.它具有与正在运行的计算机上的处理器一样多的线程.
You also have a default, namely 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.
更新:如果您确实要指定规范,尽管不建议这样做,但是您可以展开for yield
Update: If you really want to specifiy, although it's not recommended, you can unwrap the for yield
val combined = futureA.flatMap(x => futureB)(context)
这篇关于Scala:ExecutionContext用于将来的理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!