如何在不使用zip()的情况下将不同类型的Future合并为单个Future [英] How to combine Futures of different types into a single Future without using zip()
本文介绍了如何在不使用zip()的情况下将不同类型的Future合并为单个Future的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从以下代码创建类型为 Future [(Class1,Class2,Class3)]
的Future。但是,我发现这样做的唯一方法是使用zip()。我发现解决方案很难看,而且不是最佳选择。谁能启发我。
I want to create a Future of type Future[(Class1,Class2,Class3)]
from below code. However the only way I have found to do this is by using zip(). I find the solution ugly and properly not optimal. Can anybody enlightened me.
val v = for (
a <- {
val f0:Future[Class1] = process1
val f1:Future[Class2] = process2
val f2:Future[Class3] = process3
f0.zip(f1).zip(f2).map(x => (x._1._1,x._1._2,x._2))
} yield a // Future[(Class1,Class2,Class3)]
我也尝试使用 Future.sequence(List(f0,f1,f2))
但这不会作为新的Future可以使用 Future [List [U]]
的类型,其中 U
是 Class1 / 2/3
而我想要一个保留原始类型的三元组
I have also tried to use Future.sequence(List(f0, f1, f2))
but this will not work as the new Future will have type of Future[List[U]]
where U
is the lub of Class1/2/3
whereas I want a 3-tuple preserving the original types
推荐答案
val result: Future[(Class1, Class2, Class3)] = {
val f1 = process1
val f2 = process2
val f3 = process3
for { v1 <- f1; v2 <- f2; v3 <- f3 } yield (v1, v2, v3)
}
这篇关于如何在不使用zip()的情况下将不同类型的Future合并为单个Future的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文