将多个Future [Seq]连接为一个Future [Seq] [英] Concatenate many Future[Seq] into one Future[Seq]

查看:122
本文介绍了将多个Future [Seq]连接为一个Future [Seq]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

没有未来,这就是我使用 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.sequenceSeq[Future[T]]转换为Future[Seq[T]]

在您的情况下,TSeq.进行序列操作后,您将得到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]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆