Scala:ExecutionContext用于将来的理解 [英] Scala: ExecutionContext for future for-comprehension

查看:531
本文介绍了Scala:ExecutionContext用于将来的理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我制作future或应用onSuccessmap之类的方法时,我可以为其指定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用于将来的理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆