简体   繁体   中英

Reverse of Future.sequence

I know that a Future.sequence call can convert a List[Future[T]] to a Future[List[T]] , but what if I want to go the other way around?

I want to convert a Future[List[T]] into a List[Future[T]] .

The reason why I want to do this is as follows:

I send a message to an actor which uses Slick 3 to query a database. The Slick query returns list: Future[List[T]] . If I could convert this list to list: List[Future[T]] , then I would be able to do:

list.map(convertToMessage).foreach(m => m pipeTo sender())

So basically I want to convert each record extracted from the DB into a message and then send it to a calling actor.

I don't think this is possible, sorry.

A Future[List[T]] could complete with an empty list, a list with one element, or any number of elements.

So if you converted it to a List[Future[T]] , how many Futures would the list contain?

instead of using akkas pipeTo pattern, you can just do something like:

// capture the sender, before the future is started - just like pipeTo does
val s = sender()
futureOfListOfFoo.foreach { listOfFoo =>
  listOfFoo.map(convertToMessage).foreach { foo => s ! foo }
}

Why do you want to do this? What do you want to achieve? As soon as your future resolves, all of the items in the list are available so you gain little by lifting each of them into its own future.

Anyway:

import scala.concurrent._
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

// Assuming some starting future.
val foo: Future[List[String]] = Future.successful(List("foo"))

// This is pointless, because all we're doing is lifting each item in the list into its own already resolved future.
val bar: Future[List[Future[String]]] = foo.map(_.map(Future.successful))

// NB: you shouldn't use Await.
val baz: List[Future[String]] = Await.result(bar, 0.nanos)

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