问题描述
我从答案中学到的andThen
是函数编写器.
The andThen
meaning I learned from this answer is a function composer.
说
f andThen g andThen h
将等于
h(g(f(x)))
这意味着h function
将接收来自g(f(x))
但是对于Future
中的andThen
,所有以下内容的闭包然后将始终从原始Future
接收结果.
But for the andThen
in Future
, all the closure of the following andThen always receives the result from the original Future
.
Future{
1
}.andThen{ case Success(x) =>
println(x) // print 1
Thread.sleep(2000)
x * 2
}.andThen{ case Success(x) =>
println(x) // print 1
Thread.sleep(2000)
x * 2
}
比较
val func: Function1[Int, Int] = { x: Int =>
x
}.andThen { y =>
println(y) // print 1
y * 2
}.andThen { z =>
println(z) // print 2
z * 2
}
func(1)
使Future :: andThen从原始Future接收所有相同结果而不是链接Future的原因是什么?我观察到,这些链接在一起的andThen将顺序执行,因此原因可能不是出于并行目的.
What is the reason to make Future::andThen(s) receive all the same result from original Future instead of chaining Future? I've observed that these chained andThen will be executed sequentially, so the reason may not be for parallel purpose.
推荐答案
scala.concurrent.Future
设计为两种异步方法的折衷方案:
scala.concurrent.Future
is designed as compromise of two asynchronous approaches:
- Object-oriented observer which allows binding of asynchronous handlers
- Functional monad which offers rich functional composition capabilities.
所以andThen
很可能来自OOP领域.要获得与Function1.andThen
类似的结果,您可以使用 map
方法:
So andThen
is most likely from OOP universe. To gain similar similar result to Function1.andThen
you could use map
method :
Future(1).map {_ * 2}.map {_ * 2}
andThen
与onComplete
的区别仅在于一点点:结果andThen
的Future仍返回相同的结果,但是将等待直到提供的观察者返回或抛出某些东西.这就是为什么在文档中写的原因:
andThen
differs from onComplete
with one little thing: resulting Future of andThen
still returning same result, but will wait until supplied observer will return or throw something. That's why there is written in the docs:
还要注意文档中的第三行:
Also note third line from docs:
因此,对于新的Future
结果完全不执行任何操作.它自己的例外甚至无法破坏它. andThen
和onComplete
只是观察者的顺序和并行绑定.
So it' completely do nothing with new Future
's result. Could not even spoil it with it's ownt exception. This andThen
and onComplete
just sequential and parallel binding of observers.
这篇关于为什么andthen of Future不链接结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!