当我们在 Scala 中使用 Future 时,我想知道 onComplete 和 foreach 之间的区别。f onComplete (_ => doSomething(_))
和f foreach (_ => doSomething(_))
if(f.isCompleted) f onComplete (_ => doSomething(_))
非常感谢你们
最佳答案
主要区别在于onComplete
即使 future 以失败告终,回调也会被调用,而 foreach
(和 onSuccess
)函数仅在结果成功时调用。
事实上,onComplete
的参数是一个函数 Try[T] => U
:您传递的函数将被调用 Success[T]
如果 future 成功或带有 Failure
作为参数如果有异常:
val f = Future { ??? } // this future completes with a failure
// foreach only calls the callback if the future is successful
f.foreach(_ => thisWillNeverExecute())
// This will print "future failed" after the future completes
f.onComplete {
case Success(_) => println("future completed successfully")
case Failure(e) => println("future failed")
}
此外,您无需检查任何内容即可调用上述方法:
onComplete
/onSuccess
/onFailure
/foreach
都安排了一个回调,该回调在隐式 ExecutionContext
上调用你有范围,只有在 future 完成时。即使
isCompleted
你也可以调用他们为 false,它们只会在 future 成功完成或失败时执行,具体取决于您选择的那个。我们来看看他们的签名:
def onComplete[U](@f: Try[T] => U)(implicit executor: ExecutionContext): Unit
onComplete
需要一个 Try[T] => U
函数:该函数将在implicit executor
上执行当 future 完成时。参数将是 Success[T]
如果 future 成功还是Failure
如果 future 失败def onFailure[U](pf: PartialFunction[Throwable, U])(implicit executor: ExecutionContext): Unit
onFailure
参数是 PartialFunction
仅在 implicit executor
上执行如果 future 以 Throwable
失败其中pf
被定义为。和调用 onComplete 只匹配一些 Failure
基本一样s,事实上这正是它在标准库中的实现方式。 def onSuccess[U](pf: PartialFunction[T, U])(implicit executor: ExecutionContext): Unit
onSuccess
参数是,对称于 onFailure
, PartialFunction
仅在 implicit executor
上执行如果 future 成功完成并且提供 PartialFunction
是为值定义的。 def foreach[U](f: T => U)(implicit executor: ExecutionContext): Unit
foreach
与onSuccess
基本一致但它需要一个完整的功能。这意味着 f
如果 Future 成功完成,则始终执行 注意:
'onSuccess' 和 'onFailure' 将在 2.12 中被弃用。我建议你阅读 this series of posts by Viktor Klang了解您将如何受到这些变化的影响
关于scala - onComplete 和 foreach 在 Scala 中的 future 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36807848/