The andThen
这意味着我从中学到了answer https://stackoverflow.com/a/20292526/2210478是一个函数作曲家。
比如说
f andThen g andThen h
将等于
h(g(f(x)))
这意味着h function
将收到来自的输入g(f(x))
但对于andThen
in Future
,下面的所有闭包 andThen 总是收到原始结果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(s) 从原始 Future 接收所有相同结果而不是链接 Future 的原因是什么?我观察到这些链接的 andThen 将按顺序执行,因此原因可能不是出于并行目的。
scala.concurrent.Future
被设计为两种异步方法的折衷:
- 面向对象observer http://en.wikipedia.org/wiki/Observer_pattern它允许绑定异步处理程序
- 功能性monad http://en.wikipedia.org/wiki/Monad_%28functional_programming%29提供丰富的功能组合能力。
Reading Future.andThen's docs http://www.scala-lang.org/api/current/index.html#scala.concurrent.Future@andThen%5BU%5D(pf:PartialFunction%5Bscala.util.Try%5BT%5D,U%5D)(implicitexecutor:scala.concurrent.ExecutionContext):scala.concurrent.Future%5BT%5D:
将副作用函数应用于这个未来的结果,并且
返回一个新的未来以及这个未来的结果。
So andThen
最有可能来自 OOP 宇宙。为了获得类似的结果Function1.andThen
你可以用map http://www.scala-lang.org/api/current/index.html#scala.concurrent.Future@map%5BS%5D(f:T=>S)(implicitexecutor:scala.concurrent.ExecutionContext):scala.concurrent.Future%5BS%5D方法 :
Future(1).map {_ * 2}.map {_ * 2}
andThen
不同于onComplete
用一件小事:由此产生的未来andThen
仍然返回相同的结果,但会等到提供的观察者返回或抛出一些东西。这就是为什么文档中写道:
此方法允许强制执行回调
指定的顺序。
另请注意文档中的第三行:
请注意,如果链接的 andThen 回调之一抛出异常,
该异常不会传播到后续的 andThen 回调。
相反,后续的 andThen 回调将被赋予原始值
这个未来。
所以它完全与 new 无关Future
的结果。甚至不能因为它自己的例外而破坏它。这andThen
and onComplete
只是观察者的顺序和并行绑定。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)