0

I have two futures. One future (idsFuture) holds the computation to get the list of ids. The type of the idsFuture is Future[List[Int]]

Another Future(dataFuture) holds an array of A where A is defined as case class A(id: Int, data: String). The type of dataFuture is Future[Array[A]]

I want to filter dataFuture's using ids present in idsFuture.

For example-

 case class A(id: Int, data: String)
 val dataFuture = Future(Array(A(1,"a"), A(2,"b"), A(3,"c")))
 val idsFuture = Future(List(1,2))

I should get another future having Array((A(1,"a"), A(2,"b"))

I currently do

idsFuture.flatMap{
   ids => dataFuture.map(datas => datas.filter(data => ids.contains(data.id)))}

Is there a better solution?

mohit
  • 4,968
  • 1
  • 22
  • 39

1 Answers1

3

You could use for-comprehension here instead of flatMap + map like this:

for {
  ds <- dataFuture
  idsList <- idsFuture
  ids = idsList.toSet
} yield ds filter { d => ids(d.id) }

Note that apply on Set is faster then contains on List.

Community
  • 1
  • 1
senia
  • 37,745
  • 4
  • 88
  • 129