【发布时间】:2015-08-19 23:38:06
【问题描述】:
我从这个answer学到的andThen的意思是一个函数作曲家。
说出来
f andThen g andThen h
将等于
h(g(f(x)))
这意味着h function 将接收来自g(f(x)) 的输入
但是对于Future中的andThen,后面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 将按顺序执行,因此原因可能不是出于并行目的。
【问题讨论】: