I am trying to fix the following issue:
I have a Future[Map[A, B]]. For all B, I need to apply a method that convert B to a Future[C] and I want to give back a Future[Map[A, C]]
Here is the code I have so far:
def getClients(clientIds: Seq[Int]): Future[Map[Int, ClientData]] = {
def getClientData(clientInfo: ClientInfo): Future[ClientData] =
clientInfo match {
case ValidInfo(info) => getData(info)
case _ => throw new Exception
}
client.getClients(clientIds) map {
_.toMap map {
case (clientId: Int, clientInfo: ClientInfo) =>
getClientData(clientInfo) map {
clientData => (clientId, clientData)
}
}
}
}
This code is wrong as it returns a Iterable[Future[(Int, ClientData)]]
For info getClients is a thrift method that returns Future[Map[A, B]] where the Map is mutable, so I need to convert it to an immutable map first with toMap.
Thank you in advance for your help!
Step by step:
Convert
Future[Map[A, Future[B]]]toFuture[Iterable[Future[(A, B)]]]:Convert
Iterable[Future[(A, B)]]toFuture[Iterable[(A, B)]]andflattenFuture[Future[...]]usingflatMap:Convert
Iterable[(A, B)]toMap[A, B]:For
com.twitter.util.Futureyou should usecollectinstead ofsequenceandtoSeqbeforecollectsince it acceptsSeq: