简体   繁体   中英

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?

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]] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM