当我做一个future
,或应用类似的方法onSuccess
and map
,我可以为它们指定 ExecutionContext。
例如,
val f = future {
// code
} executionContext
f.map(someFunction)(executionContext)
f onSuccess {
// code
} executionContext
但是,如果我使用 future 的理解式,我如何为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中的代码?
EDIT
好的。感谢答案,我发现了一些东西。
如果我不定义或导入implicit执行上下文 (like Implicits.global
),
for 理解无法编译。这意味着,for-comparion 使用隐式 ExecutionContext。
那么,如何在没有隐式 ExecutionContext 的情况下使用 for-compression,即如何指定?
The ExecutionContext
参数实际上是implicit
。这意味着您可以:
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
。
它具有与运行机器上的处理器一样多的线程。
默认情况下,它不会被所有 Futures 使用,您仍然需要导入它。
Update:如果你确实想指定,尽管不推荐,你可以解开for yield
val combined = futureA.flatMap(x => futureB)(context)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)