Scala: ExecutionContext for future for-comprehension



当我做一个future,或者应用像onSuccessmap这样的方法时,我可以为它们指定ExecutionContext。

例如

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

但是,如果我使用未来理解,如何为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

而且,如果未指定,哪个 ExecutionContext 以 yield 运行代码?


编辑

好的。多亏了答案,我发现了一些东西。
如果我不定义或导入隐式的 ExecutionContext(如Implicits.global), 理解不编译。这意味着,对于理解,使用隐式的ExecutionContext。

那么,如何在没有隐式 ExecutionContext 的情况下使用理解,即如何指定?

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. 这具有与正在运行的计算机上的处理器一样多的线程数。

默认情况下,它不会被所有期货使用,您仍然需要导入它。

更新:如果您确实想指定,尽管不建议这样做,但您可以解开包装for yield

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

由于for推导被"映射"到map/flatMap操作,并且这些操作的ExecutionContext参数是隐式的,我想你可以尝试在本地范围内添加一个implicit val

implicit val myContext:ExecutionContext = ...

.

我不相信有"默认"隐式ExecutionContext,但最常用的是ExecutionContext.Implicits.global

最新更新