gpt4 book ai didi

scala - 为什么 Scala 的 Future.onComplete 需要一个 ExecutionContext

转载 作者:行者123 更新时间:2023-12-04 19:04:41 24 4
gpt4 key购买 nike

不能Promise.complete刚刚运行Future.onComplete的回调,而不是一路通过 ExecutionContext并且,据我所知,安排 Future.onComplete稍后的回调并可能在另一个线程中运行它?

最佳答案

您可以提供自己的ExecutionContextonComplete ,这将在同一线程上运行代码:

val immediateContext: ExecutionContext = new ExecutionContext {
def execute(runnable: Runnable) {
runnable.run()
}
def reportFailure(cause: Throwable) {}
}

你甚至可以做到 implicit ,并且对于您希望在另一个线程中执行的情况,您可以提供 scala.concurrent.ExecutionContext.global或其他一些上下文。

这是一个测试,它是如何工作的:
val immediateContext: ExecutionContext = new ExecutionContext {
override def reportFailure(cause: Throwable): Unit = {}
override def execute(runnable: Runnable): Unit = {
println("Executing")
runnable.run()
println("Executed")
}
}

def testContext(): Unit = {
println("Scheduling on an uncompleted future")
val p = Promise[Int]()
println("Scheduling")
p.future.onComplete { _ => println("Completed") }(immediateContext)
println("Scheduled")
p.complete(Success(5))

println()

println("Scheduling on an already completed future")
val p2 = Promise[Int]().complete(Success(5))
println("Scheduling")
p2.future.map { n =>
println("Mapping")
n * 2
}(immediateContext).onComplete{
case Success(n) => println(s"Completed: $n")
case _ =>
}(immediateContext)
println("Scheduled")

println()

println("Using scala.concurrent.ExecutionContext.global for comparison")
val p3 = Promise[Int]().complete(Success(5))
println("Scheduling")
p3.future.onComplete {
_ => println("Completed")
}(concurrent.ExecutionContext.global)
println("Scheduled")
}

运行 testContext()将打印
Scheduling on an uncompleted future
Scheduling
Scheduled
Executing
Completed
Executed

Scheduling on an already completed future
Scheduling
Executing
Mapping
Executed
Executing
Completed: 10
Executed
Scheduled

Using scala.concurrent.ExecutionContext.global for comparison
Scheduling
Scheduled
Completed

关于scala - 为什么 Scala 的 Future.onComplete 需要一个 ExecutionContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28051054/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com