Dima
Dima

Reputation: 40500

Future sequence to sequence of futures?

Suppose, I have an abstract "producer" instance:

  trait Producer[T] {
    def listObjectIds: Future[Seq[String]]
    def getObject(id: String): Future[T]
  }

and I need to apply some processing to each (or some) of the objects it yields. So, I do something like:

  producer
    .listObjectIds
    .map(maybeFilter)
    .map(_.map(producer.getObject))

... and end up with Future[Seq[Future[T]]] This is ok, but kinda cumbersome. I would like to get rid of the outer Future, and just have Seq[Future[T]], but can't think of a (non-blocking) transformation, that would let me do that.

Any ideas?

Upvotes: 2

Views: 3579

Answers (1)

Joe K
Joe K

Reputation: 18424

It's not possible to end up with a Seq[Future[T]]. See Reverse of Future.sequence.

But it is possible to end with a Future[Seq[T]]. Just call .flatMap(Future.sequence) on the Future[Seq[Future[T]].

Upvotes: 4

Related Questions