问题描述
没有未来,这就是我使用 flatmap
Without Future, that's how I combine all smaller Seq into one big Seq with a flatmap
category.getCategoryUrlKey(id: Int):Seq[Meta] // main method
val appDomains: Seq[Int]
val categories:Seq[Meta] = appDomains.flatMap(category.getCategoryUrlKey(_))
现在方法getCategoryUrlKey
可能会失败.我在前面放置了一个断路器,以避免在 maxFailures 之后再用于下一个元素.现在断路器不会返回Seq
,而是返回Future[Seq]
Now the method getCategoryUrlKey
could fail. I put a circuit breaker in front to avoid to call it for the next elements after an amount of maxFailures. Now the circuit breaker doesn't return a Seq
but a Future[Seq]
lazy val breaker = new akka.pattern.CircuitBreaker(...)
private def getMeta(appDomainId: Int): Future[Seq[Meta]] = {
breaker.withCircuitBreaker {
category.getCategoryUrlKey(appDomainId)
}
}
如何遍历列表appDomains
并将结果组合到一个单独的Future [Seq]中,可能将其合并到Seq中?
How to iterate through the List appDomains
and combine the result into one single Future[Seq] , possible into Seq ?
如果可以使用函数式编程,是否有一种方法可以直接转换而无需临时变量?
If Functional Programming is applicable, is there a way to directly transform without temporary variables ?
推荐答案
使用Future.sequence压缩期货序列
Future.sequence
将Seq[Future[T]]
转换为Future[Seq[T]]
在您的情况下,T
是Seq
.进行序列操作后,您将得到Seq [Seq [T]].因此,只需在使用flatten进行序列操作后将其展平即可.
In your case T
is Seq
. After the sequence operation, you will end up with Seq[Seq[T]]. So Just flatten it after the sequence operation using flatten.
def squashFutures[T](list: Seq[Future[Seq[T]]]): Future[Seq[T]] =
Future.sequence(list).map(_.flatten)
您的代码成为
Future.sequence(appDomains.map(getMeta)).map(_.flatten)
这篇关于将多个Future [Seq]连接为一个Future [Seq]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!