当我创建一个 `future`,或者应用 `onSuccess` 和 `map` 等方法时,我可以为它们指定 `ExecutionContext`。
例如,
编辑
例如,
val f = future {
// code
} executionContext
f.map(someFunction)(executionContext)
f onSuccess {
// code
} executionContext
然而,如果我使用一个future的for-comprehension,我怎样才能为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
如果没有指定,那么在yield中运行代码的ExecutionContext是什么?
编辑
好的,得到答案之后,我发现如下内容:
如果我不定义或导入隐式ExecutionContext(例如Implicits.global
),
则for-comprehension无法编译。这意味着for-comprehension使用隐式ExecutionContext。
那么,如何在没有隐式ExecutionContext的情况下使用for-comprehension,即如何指定ExecutionContext?
implicit
,则for
推导式无法编译。请查看我的答案以了解其根本原因。 - mikołakfor
推导式(在这种情况下,flavian的答案有效),还是多个连续的for
推导式?为了确保准确性,请确认一下。 - mikołak