zella
zella

Reputation: 4685

How to implement futures composition

I have a method:

def findUserById(id: String): Future[Option[User]]

Now i want make another method, based on it:

def findUserById(ids: Seq[String]): Future[Seq[User]]

But i have some problem with using futures. How to implement futures composition properly?

I have an implementation(not tested), but i think it can be made easier. Also i'm not sure about performance of that implementation:

  override def findUsersById(ids: Seq[String]): Future[Seq[User]] = {
    val futures = ids.map(id => findUserById(id))
    val filtered = Future.sequence(futures).map(_.filterNot(_.isEmpty)).map(_.map(_.get))
    filtered
  }

Upvotes: 2

Views: 83

Answers (1)

Kolmar
Kolmar

Reputation: 14224

You can replace sequence+map with traverse, and filter+map with flatten:

def findUsersById(ids: Seq[String]): Future[Seq[User]] = 
  Future.traverse(ids)(findUserById).map(_.flatten)

In general Future.traverse is more succinct than Future.sequence, and is a bit more effective, because it avoids creating an intermediate Seq[Future[T]].

Upvotes: 5

Related Questions