tbere
tbere

Reputation: 135

How do I flatten an Array[Future[Seq[T]]]

im searching for 2 hours now and don't get any answer to my problem. I want to have only one Seq to return but have an Array of Seq, so now my question is how do i extract the seq out of the array

def searchUsers(query: String): Future[Seq[User]] = {
  var queryStrings: Array[String] = query.split(" ")
  var users = ArrayBuffer[User]()
  queryStrings.map(Users.search(_))
}

Maybe someone could help me

Cheers

Update:

sorry that my question is not that precisely that it should be. My Problem is that i want to have the return value as Future[Seq[User]] and because of the query.split (i have to map it) it is Array[Future[Seq[User]]]

The error is Expression of type Array[Future[Seq[User]]] doesn't conform to expected type Future[Seq[User]]

Upvotes: 2

Views: 742

Answers (2)

Kevin Meredith
Kevin Meredith

Reputation: 41909

I don't like the x.toList in my answer, but posting to show the usage of Future#traverse:

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

def f[A, B](x: Array[A], f: A => Future[Seq[B]]): Future[Seq[B]] = 
  Future.traverse[A, Seq[B], Seq](x.toList)(f).map(_.flatten)

scala> f( Array(1,2,3), { x: Int => Future.successful(List(x)) } )
res2: scala.concurrent.Future[Seq[Int]] = Success(List(1, 2, 3))

Upvotes: 0

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

In order to flatten the Array[Future[Seq[User]], we can first use Future.sequence to get a Future[Array[Seq[User]] and then flatten it to get Future[Seq[User]]:

Future
 .sequence[Seq[User], Seq](queryStrings.map(Users.search))
 .map(_.flatten)

Upvotes: 4

Related Questions