Nae*_*mul 7 scala future for-comprehension executioncontext
当我做一个future,或者应用类似的方法onSuccess和map,我能为他们指定的ExecutionContext.
例如,
val f = future {
// code
} executionContext
f.map(someFunction)(executionContext)
f onSuccess {
// code
} executionContext
Run Code Online (Sandbox Code Playgroud)
但是,如果我使用了对未来的理解,我该如何为该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
Run Code Online (Sandbox Code Playgroud)
而且,如果没有指定,ExecutionContext在yield中运行代码是什么?
好.感谢答案,我找到了一些东西.
如果我没有定义或导入隐式 ExecutionContext(如Implicits.global),则for-comprehension不会编译.这意味着,for-comprehension使用隐式ExecutionContext.
那么,如何在没有隐式ExecutionContext的情况下使用for-comprehension,即如何指定?
该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.
}
Run Code Online (Sandbox Code Playgroud)
你也有默认,即scala.concurrent.ExecutionContext.Implicits.global.它具有与正在运行的计算机上的处理器一样多的线程.
默认情况下,所有期货都不会使用它,您仍然需要导入它.
更新:如果你真的想要指定,虽然不推荐,你可以解开for yield
val combined = futureA.flatMap(x => futureB)(context)
Run Code Online (Sandbox Code Playgroud)